Tim
Tim

Reputation: 99428

How to define a member function of a class at the class level or at the level of instance objects?

In Python 2.7, when defining a class, how can we define

When using a given class, how can we tell if a member function is at the level of class or at the level of the class' instance objects?

For example, in the Python standard library, the setUp() from TestCase is called for each instance object of TestCase, i.e. at the level of instance objects, while class level fixtures are implemented in TestSuite. When the test suite encounters a test from a new class then tearDownClass() from the previous class (if there is one) is called, followed by setUpClass() from the new class.

Thanks.

Upvotes: 0

Views: 289

Answers (1)

galaxyan
galaxyan

Reputation: 6121

The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.

For more information on class methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

https://docs.python.org/2/library/functions.html#classmethod

class A:
...    message = "class message"
... 
...    @classmethod
...    def classLevel(cls):
...       print(cls.message)
... 
...    def instanceLevel(self, msg):
...       self.message = msg
...       print(self.message)
>>> a= A()
>>> a.instanceLevel('123')
123
>>> A.classLevel()
class message
>>> a.classLevel()
class message
>>> A.instanceLevel()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method instanceLevel() must be called with A instance as first argument (got nothing instead)


    A.__dict__
{'classLevel': <classmethod object at 0x4E974BB0>, '__module__': '__main__', 'instanceLevel': <function instanceLevel at 0x550C8530>, 'message': 'class message', '__doc__': None}

Upvotes: 2

Related Questions