[英]how to create an instance of class python
我正在学习使用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
命名为(全部为小写),则模块和包含的类是两个不同的概念,这可能会更加明显。 :-)
简单来说,这行代码:
import Counter
仅使Counter
模块可用。 如果要使用其中包含的一种工具(例如Counter
类),则需要使用模块名称对其进行限定:
import Counter
h = Counter.Counter()
或者,您可以直接导入所需的工具:
from Counter import Counter
h = Counter()
这是有关在Python中导入的参考。
此外,PEP 8(Python代码的官方样式指南)指出, 模块名称应小写 :
模块应使用简短的全小写名称。 如果模块名称可以提高可读性,则可以在模块名称中使用下划线。 尽管不鼓励使用下划线,但Python软件包也应使用短的全小写名称。
因此,最好将Counter
模块重命名为counter
。
您需要Counter.Counter
,因为您的文件也被命名为Counter.py
。
如果不调用h = Counter.Counter()
,则基本上是在尝试将模块作为函数调用:
>>> import math
>>> math()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
您有两个选择。
1.调用import Counter
,然后调用h = Counter.Counter()
import Counter
h = Counter.Counter()
print(h.getValue())
2. from Counter import Counter
调用,然后调用h = Counter()
from Counter import Counter
h = Counter()
print(h.getValue())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.