简体   繁体   中英

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. 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. :-)

In simple terms, the line:

import Counter

only makes the module Counter available for use. 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:

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 .


Also, PEP 8, the official style guide for Python code, states that module names should be lowercase :

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.

Therefore, it would be best if you renamed the Counter module to counter .

You want Counter.Counter instead, because your file is named Counter.py as well.

If you don't call h = Counter.Counter() , you are basically trying to invoke the module as a function:

>>> 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()

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

2. Call from Counter import Counter and then call h = Counter()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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