简体   繁体   English

如何创建python类的实例

[英]how to create an instance of class python

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. 我正在学习使用Python 3.4.1的Python中的类,并尝试创建一个类,然后从该类中调用方法。 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. 我可以在shell中输入import Counter,但是当我到达h = Counter()时,会遇到相同的错误。 I know I'm doing something wrong, but what? 我知道我做错了什么,但是呢?

You named your module Counter too; 您也将模块命名为Counter 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. 这就是Python样式指南建议您为模块使用所有小写名称的原因。 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. 在Python中,模块的名字不必匹配类包含的,你是不是局限于一个类模块中。 A module can contain just functions or any other Python object too. 模块可以只包含函数或任何其他Python对象。

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. 如果您将模块文件counter命名为(全部为小写),则模块和包含的类是两个不同的概念,这可能会更加明显。 :-) :-)

In simple terms, the line: 简单来说,这行代码:

import Counter

only makes the module Counter available for use. 仅使Counter模块可用。 If you want to use one of the tools that it contains, such as the class Counter , you need to qualify it with the module name: 如果要使用其中包含的一种工具(例如Counter类),则需要使用模块名称对其进行限定:

import Counter
h = Counter.Counter()

Or, you can import the tools you want directly: 或者,您可以直接导入所需的工具:

from Counter import Counter
h = Counter()

Here is a reference on importing in Python . 这是有关在Python中导入的参考。


Also, PEP 8, the official style guide for Python code, states that module names should be lowercase : 此外,PEP 8(Python代码的官方样式指南)指出, 模块名称应小写

Modules should have short, all-lowercase names. 模块应使用简短的全小写名称。 Underscores can be used in the module name if it improves readability. 如果模块名称可以提高可读性,则可以在模块名称中使用下划线。 Python packages should also have short, all-lowercase names, although the use of underscores is discouraged. 尽管不鼓励使用下划线,但Python软件包也应使用短的全小写名称。

Therefore, it would be best if you renamed the Counter module to counter . 因此,最好将Counter模块重命名为counter

You want Counter.Counter instead, because your file is named Counter.py as well. 您需要Counter.Counter ,因为您的文件也被命名为Counter.py

If you don't call h = Counter.Counter() , you are basically trying to invoke the module as a function: 如果不调用h = Counter.Counter() ,则基本上是在尝试将模块作为函数调用:

>>> import math
>>> math()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable

You have two options. 您有两个选择。

1. Call import Counter and then call h = Counter.Counter() 1.调用import Counter ,然后调用h = Counter.Counter()

import Counter
h = Counter.Counter()
print(h.getValue())

2. Call from Counter import Counter and then call h = Counter() 2. from Counter import Counter调用,然后调用h = Counter()

from Counter import Counter
h = Counter()
print(h.getValue())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM