1 Part 1 Beginning Python
1.7 Organization
1.7.2 Classes and instances
foreground_color: "black"
background_color: "green"
link_color: "blue"
visited_link_color: "red"
foreground_color: "black"
background_color: "white"
link_color: "gray"
visited_link_color: "yellow"
1.7.2 Classes and instances
1.7.2.1 A basic class
Define a basic class as follows:
class Basic:
def __init__(self, name):
self.name = name def show(self):
print 'Basic name: %s' % self.name def test():
obj1 = Basic('Apricot') obj1.show()
test()
Running the above example produces the following:
Basic name: Apricot
Explanation:
● Methods are added to the class with def. The first argument to a method is the class instance. By convention it is spelled "self".
● The constructor for a class is a method named __init__.
● The self variable must be explicitly listed as the first argument to a method. You could spell it differently from "self", but don't do so.
● Instance variables are referred to with "self.XXX". Notice how in our example an argument to the constructor is saved as an instance variable.
● An instance is created by "calling" the class. For example: obj = Basic('Apricot').
● In addition to __init__ there are other special method names of the form
"__XXX__", which are used to customize classes and their instances. These are described at Python Language Reference: Special method names
http://docs.python.org/reference/datamodel.html#specialmethodnames
<http://docs.python.org/reference/datamodel.html#specialmethodnames>_.
A few more notes on self:
● self is a reference to the instance. Think of it (in part) as a reference to the container for the data or state for the object.
● In many objectoriented programming languages, the instance is hidden in the method definitions. These languages typically explain this by saying something like "The instance is passed as an implicit first argument to the method."
● In Python, the instance is visible and explicit in method definitions. You must explicitly declare the instance as the first parameter of each (instance) method.
This first parameter is (almost) always spelled "self".
1.7.2.2 Inheritance
Define a class Special that inherits from a superclass Basic as follows:
class Basic:
def __init__(self, name):
self.name = name def show(self):
print 'Basic name: %s' % self.name class Special(Basic):
def __init__(self, name, edible):
Basic.__init__(self, name) self.upper = name.upper() self.edible = edible def show(self):
Basic.show(self)
print 'Special upper name: %s.' % self.upper if self.edible:
print "It's edible."
else:
print "It's not edible."
def edible(self):
return self.edible def test():
obj1 = Basic('Apricot') obj1.show()
print '=' * 30
obj2 = Special('Peach', 1) obj2.show()
test()
Running this example produces the following:
Basic name: Apricot
==============================
Basic name: Peach
Special upper name: PEACH. It's edible.
Comments:
● The superclass is listed after the class name in parentheses. For multiple inheritence, separate the superclasses with commas.
● Call a method in the superclass, bypassing the method with the same name in the subclass, from the subclass by using the superclass name. For example:
Basic.__init__(self, name) and Basic.show(self).
● In our example (above), the subclass (Special) specializes the superclass (Basic) by adding additional member variables (self.upper and
self.edible) and by adding an additional method (edible).
1.7.2.3 Class data
A class data member is a member that has only one value for the class and all its instances. Here is an example from the Python FAQ at
http://www.python.org/doc/FAQ.html:
class C:
count = 0 # number of times C.__init__ called def __init__(self):
C.count += 1 def getcount(self):
return C.count # or return self.count def test():
c1 = C()
print 'Current count:', c1.getcount() c2 = C()
print 'Current count:', c2.getcount() test()
Running this example produces:
Current count: 1 Current count: 2
1.7.2.4 Static methods and class methods
Newstyle classes can have static methods and class methods.
A newstyle class is a class that inherits directly or indirectly from object or from a built
in type.
Here is an example that shows how to define static methods and class methods:
class Advanced(object):
def __init__(self, name):
self.name = name def Description():
return 'This is an advanced class.' def ClassDescription(cls):
return 'This is advanced class: %s' % repr(cls) Description = staticmethod(Description)
ClassDescription = classmethod(ClassDescription) obj1 = Advanced('Nectarine')
print obj1.Description() print obj1.ClassDescription() print '=' * 30
print Advanced.Description()
print Advanced.ClassDescription()
Running the above produces the following output:
This is an advanced class.
This is advanced class: <class __main__.Advanced at 0x401c926c>
==============================
This is an advanced class.
This is advanced class: <class __main__.Advanced at 0x401c926c>
Notes:
● The class inherits from class object, which makes it a newstyle class.
● Create a static method with x = staticmethod(y), where y is a normal method but without the self/first parameter.
● Create a class method with x = classmethod(y), where y is a normal method.
The difference between static and class methods is that a class method receives the class (not the instance) as its first argument. A summary:
● A normal/standard method always receives an instance as its first argument.
● A class method always receives the class as its first argument.
● A static method does not (automatically) receive either the instance or the class as the first argument.
● You can call static and class methods using either an instance or a class. In our example either "obj1.Description()" or "Advanced.Description()" will work.
● You should also review the relevant standard Python documentation on the classmethod and staticmethod builtin functions, which you can find at Python Library Reference 2.1 Builtin Functions
http://docs.python.org/library/functions.html.
By now, you are likely to be asking: "Why and when should I use class methods and static methods?" Here is a bit of guidance:
● Most of the time, almost always, implement plain instance methods. Implement an instance method whenever the method needs access to the values that are specific to the instance or needs to call other methods that have access to instance specific values. If the method needs self, then you probably need an instance
method.
● Implement a class method (1) when the method does not need access to instance variables and (2) when you do not want to require the caller of the method to create an instance and (3) when the method needs access to class variables. A class method may be called on either an instance or the class. A class method gets the class as a first argument, whether it is called on the class or the instance. If the method needs access to the class but does not need self, then think class method.
● Implement a static method if you merely want to put the code of the method within the scope of the class, perhaps for purposes of organizing your code, but the method needs access to neither class nor instance variables (though you can access class variables through the class itself). A static method may be called on either an instance or the class. A static method gets neither the class nor the instance as an argument.
To summarize:
Implement an instance method, unless ... the method needs access to class variables but not instance variables, then implement a class method, unless ... the method needs access to neither instance variables nor class variables and you still want to include it within the class definition, then implement a static method.
Above all, write clear, plain code that will be understandable to your readers. Do not use a more confusing language feature and do not force your readers to learn a new language feature unles you have a good reason.
1.7.2.5 Properties
A newstyle class can have properties. A property is an attribute of a class that is associated with a getter and a setter function.
Declare the property and its getter and setter functions with property().
Here is an example:
class A(object):
count = 0
def __init__(self, name):
self.name = name def set_name(self, name):
print 'setting name: %s' % name self.name = name
def get_name(self):
print 'getting name: %s' % self.name return self.name
objname = property(get_name, set_name) def test():
a = A('apple')
print 'name: %s' % a.objname a.objname = 'banana'
print 'name: %s' % a.objname test()
Running the above produces the following output:
getting name: apple name: apple
setting name: banana getting name: banana name: banana
Notes:
● The class inherits from class object, which makes it a newstyle class.
● When a value is assigned to a property, the setter method is called.
● When the value of a property is accessed, the getter method is called.
● You can also define a delete method and a documentation attribute for a property.
For more information, visit 2.1 Builtin Functions and look for property.