Python-Ref > Object oriented programming > Basics > Classmethods
 
 

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

Classmethods

Methods that work on class, not instance.
Just as class attributes work on the class itself and not the instance as normal attributes, classmethods work with the class and not the instance. Because of this classmethods are limited to class attributes only.
Expand/Shrink
  1   class ObjectWithId( object):
  2     """a simple object with ID."""
  3   
  4     last_id = 0
  5   
  6     @classmethod
  7     def get_new_id( self):
  8       self.last_id += 1
  9       return self.last_id
 10   
 11     def __init__( self):
 12       self.id = self.get_new_id()
 13   
 14     def __str__( self):
 15       return "Dummy object %d" % self.id
 16   
 17   
 18   objs = []
 19   for i in range( 10):
 20     o = ObjectWithId()
 21     print o
 22     
 23   print ObjectWithId.last_id
 24   print ObjectWithId.get_new_id()
stdout:
Dummy object 1
Dummy object 2
Dummy object 3
Dummy object 4
Dummy object 5
Dummy object 6
Dummy object 7
Dummy object 8
Dummy object 9
Dummy object 10
10
11
Doba běhu: 22.3 ms
Classmethods are often used by so called singletons - objects that should be present only once in your applications and their state should be shared by the whole application. The code below demonstrates two of such objects.
Expand/Shrink
  1   import os
  2   
  3   class TempManager( object):
  4     """manages temp file creation"""
  5   
  6     last_id = 0
  7     temp_dir = "tmp"
  8     name_base = "temp"
  9   
 10     @classmethod
 11     def get_new_tempfile( self):
 12       self.last_id += 1
 13       return os.path.join( self.temp_dir, self.name_base+str( self.last_id))
 14   
 15   
 16   objs = []
 17   for i in range( 10):
 18     fname = TempManager.get_new_tempfile()
 19     print fname
 20     
 21   TempManager.name_base = "temporary"
 22   TempManager.temp_dir = "mytmp"
 23   print TempManager.get_new_tempfile()
stdout:
tmp/temp1
tmp/temp2
tmp/temp3
tmp/temp4
tmp/temp5
tmp/temp6
tmp/temp7
tmp/temp8
tmp/temp9
tmp/temp10
mytmp/temporary11
Doba běhu: 25.8 ms
Expand/Shrink
  1   import os
  2   
  3   class Screen( object):
  4     """manages information about the screen"""
  5   
  6     dpi = 96
  7   
  8     @classmethod
  9     def px_to_cm( self, px):
 10       return px / (self.dpi / 2.54)
 11   
 12   
 13   print Screen.px_to_cm( 96)
 14   print Screen.px_to_cm( 200)
 15   Screen.dpi = 72
 16   print Screen.px_to_cm( 200)
stdout:
2.54
5.29166666667
7.05555555556
Doba běhu: 22.9 ms
The following piece of code shows a typical error a beginner might make when attempting to use classmethods.
Expand/Shrink
  1   class Person( object):
  2   
  3     def __init__( self, name):
  4       self.name = name
  5   
  6     @classmethod
  7     def class_get_name( self):
  8       return self.name # error, class Person has no attribute name 
  9   
 10     def get_name( self):
 11       return self.name
 12   
 13     def __str__( self):
 14       return self.name
 15   
 16   a = Person( "Arthur Dent")
 17   print a.get_name()
 18   print a.class_get_name()
stdout:
Arthur Dent
stderr:
Traceback (most recent call last):
  File "oop-classmethods1-4.py", line 18, in ?
    print a.class_get_name()
  File "oop-classmethods1-4.py", line 8, in class_get_name
    return self.name # error, class Person has no attribute name #@+
AttributeError: type object 'Person' has no attribute 'name'
Doba běhu: 28.4 ms