我正在学习使用Python 3.4.1的Python中的类,并尝试创建一个类,然后从该类中调用方法。我已经看过与此相关的其他问题,但不幸的是,我似乎无法使其正常工作。这是我的课(直接从书中复制)
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
这就是我从另一个文件(在同一文件夹中)调用它的方式:
import Counter
h = Counter()
print(h.getValue())
这是我得到的错误:
Traceback (most recent call last):
File "C:/Python34/learning/classtest.py", line 3, in <module>
h = Counter()
TypeError: 'module' object is not callable
我可以在shell中键入import Counter,但是当我进入h = Counter()时,会遇到相同的错误。我知道我做错了什么,但是呢?
您也为模块命名Counter
;该类包含在模块中:
import Counter
h = Counter.Counter()
或者,从模块中导入类:
from Counter import Counter
h = Counter()
这就是Python样式指南建议您为模块使用所有小写名称的原因。在Python中,模块的名称并没有必须匹配类包含的,你是不是局限于一个类模块中。一个模块也可以只包含函数或任何其他Python对象。
counter
取而代之的是,如果您将模块文件命名为全小写,则模块和包含的类是两个不同的概念,这可能会更加明显。:-)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句