Python-Ref > Object oriented programming > Basics > Class attributes
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Class attributes

What is a difference between attributes and class attributes
As well as there are data associated with every object (instance) in its attributes, it is also possible to create attributes that are attached to the class itself, not a concrete instance. This has several important effects.
  • Class attributes can be accessed without the need to create an instance.
  • Class attribute value is the same for all derived instances.
  • Change of class attribute influences all derived instances.
Please note that the value of an class attribute must be changed directly on the class. Changing it on the instance level just creates an instance attribute with the same name that overshadows the class attribute for that instance.
Expand/Shrink
Zdroj: (oop4-1.py)
  1   class Circle:
  2   
  3     default_color = "black"  # class attribute
  4   
  5     def __init__( self, size=1, color=None):
  6       self.size = size
  7       if color == None:
  8         self.color = self.default_color
  9       else:
 10         self.color = color
 11   
 12   
 13   print Circle.default_color
 14   # print Circle.size   # - this would crash
 15   c1 = Circle( size=2, color="red")
 16   c2 = Circle( size=3)
 17   c3 = Circle()
 18   
 19   print "c1", c1.default_color, c1.color
 20   print "c2", c2.default_color, c2.color
 21   print "c3", c3.default_color, c3.color
 22   print "----------"
 23   
 24   Circle.default_color = "blue"
 25   print "c1", c1.default_color, c1.color
 26   print "c2", c2.default_color, c2.color
 27   print "c3", c3.default_color, c3.color
 28   print "----------"
 29   
 30   # here instance attribute is created, overshadowing the class attribute
 31   c1.default_color = "green"
 32   print "c1", c1.default_color, c1.color
 33   print "c2", c2.default_color, c2.color
 34   print "c3", c3.default_color, c3.color
 35   print "Circle", Circle.default_color
stdout:
black
c1 black red
c2 black black
c3 black black
----------
c1 blue red
c2 blue black
c3 blue black
----------
c1 green red
c2 blue black
c3 blue black
Circle blue
Doba běhu: 20.9 ms
The following example shows how class attributes can be combined with a inherited method to influence the behaviour of classes without reimplementation of methods in children.
Expand/Shrink
Zdroj: (oop4-2.py)
  1   class Animal:
  2   
  3     sound = ""
  4   
  5     def make_sound( self):
  6       print self.sound
  7   
  8   
  9   class Lion( Animal):
 10   
 11     sound = "ROAR"
 12   
 13   
 14   class Mouse( Animal):
 15   
 16     sound = "squeak"
 17   
 18   
 19   l = Lion()
 20   m = Mouse()
 21   l.make_sound()
 22   m.make_sound()
stdout:
ROAR
squeak
Doba běhu: 15.1 ms