avatar

class attribute

Here is an understanding of class attribute.

It is so easy to mess up between class attribute and instance attribute.

Below is a very good example between the two concepts.

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class InstanceCounter(object):
count = 0

def __init__(self,value):
self.value = value
InstanceCounter.count += 1

a = InstanceCounter(5)
b = InstanceCounter(10)
c = InstanceCounter(15)

for obj in (a, b, c):
print("Instance attribute value: {}".format(obj.value))
print("Instance attribute value: {}".format(InstanceCounter.count))
Instance attribute value: 5
Instance attribute value: 3
Instance attribute value: 10
Instance attribute value: 3
Instance attribute value: 15
Instance attribute value: 3

As we can see, the class attribute InstanceCounter.count incremented after each instantiate of a new object.

The trick is that, python treats everything as an ‘object.’.

Not only an instance of class is an object, but the class itself is also an object.

‘class InstanceCounter(object)’ means instantiating a ‘class’ type object named InstanceCounter

Let us print the methods of the InstanceCounter:

python
1
print(InstanceCounter)
<class '__main__.InstanceCounter'>
python
1
print(dir(InstanceCounter))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'count']

Clearyly, InstanceCounter is also an object.

python
1
2
3
4
class Datastorage(object):
a = 0
b = 1
c = 2

According to this concept, the class attribute will normally be used as static variables among all the instances.


评论