I am learning about classes in Python, using Python 3.4.1 and am attempting to make a class and then call the methods from that class. I have looked at other questions related to this and unfortunately, I can't seem to make it work. Here is my class (copied straight from the book)
class Counter(object):
"""Models a counter"""
instances = 0
def __init__(self):
"""Sets up counter"""
Counter.instances += 1
self.reset()
def reset(self):
"""Sets counter to 0"""
self._value=0
def increment(self, amount = 1):
"""Adds amount to counter"""
self._value += amount
def decrement(self, amount = 1):
"""Subtracts amount from counter"""
self._value -= amount
def getValue(self):
return self._value
def __str__(self):
return str(self._value)
def __eq__(self, other):
"""Returns True if self == other and False if not"""
if self is other:
return True
if type(self)!=type(other):
return False
return self._value==other._value
and this is how I'm calling it from another file (in the same folder):
import Counter
h = Counter()
print(h.getValue())
and this is the error I'm getting:
Traceback (most recent call last):
File "C:/Python34/learning/classtest.py", line 3, in <module>
h = Counter()
TypeError: 'module' object is not callable
I can type import Counter just fine into the shell, but when I get to h = Counter() I get the same error. I know I'm doing something wrong, but what?
You named your module Counter
too; the class is contained in the module:
import Counter
h = Counter.Counter()
Alternatively, import the class from the module:
from Counter import Counter
h = Counter()
This is why the Python style guide recommends you use all lower-case names for your modules. In Python, the module name does not have to match the class contained, and you are not limited to just one class in a module. A module can contain just functions or any other Python object too.
Had you named your module file counter
(all lowercase) instead, it would perhaps have been more obvious that the module and contained class are two distinct concepts. :-)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments