Python Object-Oriented Programming
Python has been an object-oriented language since its design; because of this, creating classes and objects in Python is easy. This chapter explains Python's object-oriented programming in detail.
If you have not encountered object-oriented programming languages before, you may need to learn some basic features of object-oriented languages first and form a basic object-oriented concept in your mind, which will help you learn Python's object-oriented programming more easily.
Next let's take a brief look at some basic features of object orientation.
Introduction to object-oriented technology
- **Class:** describes a collection of objects with the same attributes and methods. It defines the attributes and methods common to every object in the collection. An object is an instance of a class.
- **Class variable:** a class variable is shared among all instantiated objects. It is defined in the class but outside function bodies. Class variables are usually not used as instance variables.
- **Data members:** Class variables or instance variables, used to handle data related to the class and its instance objects.
- **Method overriding:** if a method inherited from the parent class does not meet the subclass's needs, it can be rewritten; this process is called method overriding.
- **Local variable:** a variable defined in a method, which applies only to the current instance of the class.
- **Instance variables:** In a class declaration, attributes are represented by variables. Such variables are called instance variables; they are declared inside the class declaration but outside the other member methods of the class.
- **Inheritance:** a derived class inherits the fields and methods of a base class. Inheritance also allows treating an object of a derived class as an object of the base class. For example, in a design where an object of type Dog derives from the Animal class, this models an "is-a" relationship (Dog is an Animal).
- **Instantiation:** creating an instance of a class, a concrete object of the class.
- **Method:** a function defined inside a class.
- **Object:** an instance of a data structure defined by a class. An object includes two kinds of data members (class variables and instance variables) and methods.
Creating a Class
Use the class statement to create a new class. After class comes the name of the class, followed by a colon:
class ClassName:
'类的帮助信息' #类文档字符串
class_suite #类体
The help information for a class can be viewed through ClassName.__doc__.
The class_suite consists of class members, methods, and data attributes.
Example
The following is an example of a simple Python class:
Example
#!/usr/bin/python
-- coding: UTF-8 --
class
Employee
:
'
The base class for all employees
'
empCount
=
0
def
init
(
self
,
name
,
salary
)
:
self
.
name
=
name
self
.
salary
=
salary
Employee
.
empCount
+=
1
def
displayCount
(
self
)
:
"
Total Employee %d
"
%
Employee
.
empCount
def
displayEmployee
(
self
)
:
"
Name :
"
,
self
.
name
,
"
, Salary:
"
,
self
.
salary
-
The variable empCount is a class variable whose value is shared among all instances of this class. You can access it inside or outside the class using Employee.empCount.
-
The first method, __init__(), is a special method known as the class's constructor or initialization method. It is called when an instance of the class is created.
-
self represents the instance of the class. self is required when defining class methods, although you do not need to pass a corresponding argument when calling them.
self represents the instance of the class, not the class itself
Methods of a class differ from ordinary functions in only one special way - they must have an extrafirst parameter name, which by convention is named self.
class
Test
:
def
prt
(
self
)
:
(
self
)
(
self
.
class
)
t
=
Test
(
)
t
.
prt
(
)
The example above produces:
<__main__.Test instance at 0x10d066878>
__main__.Test
From the execution result it is clear that self represents the instance of the class and the address of the current object, while self.class points to the class.
self is not a Python keyword; we can replace it with runoob and it still works:
Example
class
Test
:
def
prt
(
runoob
)
:
(
runoob
)
(
runoob
.
class
)
t
=
Test
(
)
t
.
prt
(
)
The example above produces:
<__main__.Test instance at 0x10d066878>
__main__.Test
Creating Instance Objects
To instantiate a class, other programming languages generally use the keyword new, but Python has no such keyword. Class instantiation is similar to a function call.
The following uses the class name Employee to instantiate, and through the init method receives parameters.
"创建 Employee 类的第一个对象"
emp1 = Employee("Zara", 2000)
"创建 Employee 类的第二个对象"
emp2 = Employee("Manni", 5000)
Accessing Attributes
You can use the dot . to access an object's attributes. Use the class name as follows to access class variables:
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Complete example:
Example
#!/usr/bin/python
-- coding: UTF-8 --
class
Employee
:
'
The base class for all employees
'
empCount
=
0
def
init
(
self
,
name
,
salary
)
:
self
.
name
=
name
self
.
salary
=
salary
Employee
.
empCount
+=
1
def
displayCount
(
self
)
:
"
Total Employee %d
"
%
Employee
.
empCount
def
displayEmployee
(
self
)
:
"
Name :
"
,
self
.
name
,
"
, Salary:
"
,
self
.
salary
"
Create the first object of the Employee class
"
emp1
=
Employee
(
"
Zara
"
,
2000
)
"
Create the second object of the Employee class
"
emp2
=
Employee
(
"
Manni
"
,
5000
)
emp1
.
displayEmployee
(
)
emp2
.
displayEmployee
(
)
"
Total Employee %d
"
%
Employee
.
empCount
The output of executing the above code is as follows:
Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2
You can add, delete, and modify class attributes, as shown below:
emp1.age = 7 # 添加一个 'age' 属性
emp1.age = 8 # 修改 'age' 属性
del emp1.age # 删除 'age' 属性
You can also use the following functions to access attributes:
- getattr(obj, name[, default]): Accesses an object's attribute.
- hasattr(obj,name): Checks whether an attribute exists.
- setattr(obj,name,value): Sets an attribute. If the attribute does not exist, a new one will be created.
- delattr(obj, name): Deletes an attribute.
hasattr
(
emp1
,
'
age
'
)
Returns True if the 'age' attribute exists.
getattr
(
emp1
,
'
age
'
)
Returns the value of the 'age' attribute
setattr
(
emp1
,
'
age
'
,
8
)
Adds the attribute 'age' with value 8
delattr
(
emp1
,
'
age
'
)
Deletes the attribute 'age'
Python Built-in Class Attributes
- dict : Class attribute (contains a dictionary consisting of the class's data attributes)
- doc : The class's docstring
- name: The class name
- module: The module in which the class is defined (the full name of the class is 'main.className'. If the class is located in an imported module mymod, then className.module equals mymod)
- bases : A tuple containing all the base classes of the class
An example of calling Python built-in class attributes is as follows:
Example
#!/usr/bin/python
-- coding: UTF-8 --
class
Employee
:
'
The base class for all employees
'
empCount
=
0
def
init
(
self
,
name
,
salary
)
:
self
.
name
=
name
self
.
salary
=
salary
Employee
.
empCount
+=
1
def
displayCount
(
self
)
:
"
Total Employee %d
"
%
Employee
.
empCount
def
displayEmployee
(
self
)
:
"
Name :
"
,
self
.
name
,
"
, Salary:
"
,
self
.
salary
"
Employee.doc:
"
,
Employee
.
doc
"
Employee.name:
"
,
Employee
.
name
"
Employee.module:
"
,
Employee
.
module
"
Employee.bases:
"
,
Employee
.
bases
"
Employee.dict:
"
,
Employee
.
dict
The output of executing the above code is as follows:
Employee.__doc__: 所有员工的基类
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount': , 'empCount': 0, 'displayEmployee': , '__doc__': '\xe6\x89\x80\xe6\x9c\x89\xe5\x91\x98\xe5\xb7\xa5\xe7\x9a\x84\xe5\x9f\xba\xe7\xb1\xbb', '__init__': }
Python Object Destruction (Garbage Collection)
Python uses the simple technique of reference counting to track and collect garbage.
Inside Python, a record is kept of how many references each in-use object has.
An internal tracking variable called a reference counter.
When an object is created, a reference count is created. When the object is no longer needed - that is, when its reference count becomes 0 - it is garbage collected. However, collection is not 'immediate'; the interpreter reclaims the memory occupied by the garbage object at an appropriate time.
a = 40 # 创建对象 <40>
b = a # 增加引用, <40> 的计数
c = [b] # 增加引用. <40> 的计数
del a # 减少引用 <40> 的计数
b = 100 # 减少引用 <40> 的计数
c[0] = -1 # 减少引用 <40> 的计数
The garbage collection mechanism targets not only objects with a reference count of 0, but also handles circular references. A circular reference refers to a situation where two objects reference each other but no other variables reference them. In this case, reference counting alone is not enough. Python's garbage collector is actually a reference counter plus a cyclic garbage collector. As a supplement to reference counting, the garbage collector also keeps an eye on objects that have been allocated in large numbers (i.e., those not destroyed by reference counting). In this situation, the interpreter will pause and try to clean up all unreferenced cycles.
Example
The destructor del , __del__ is called when the object is destroyed. When the object is no longer in use, the __del__ method runs:
Example
#!/usr/bin/python
-- coding: UTF-8 --
class
Point
:
def
init
(
self
,
x
=
0
,
y
=
0
)
:
self
.
x
=
x
self
.
y
=
y
def
del
(
self
)
:
class_name
=
self
.
class
.
name
class_name
,
"
Destroy
"
pt1
=
Point
(
)
pt2
=
pt1
pt3
=
pt1
id
(
pt1
)
,
id
(
pt2
)
,
id
(
pt3
)
Print the object's id
del
pt1
del
pt2
del
pt3
The above example produces the following result:
3083401324 3083401324 3083401324
Point 销毁
**Note:** Usually you need to define a class in a separate file,
Class Inheritance
One of the main benefits of object-oriented programming is code reuse, and one way to achieve this reuse is through inheritance.
A new class created through inheritance is called aSubclassorderived class, and the class being inherited from is called abase class, Parent Classorsuperclass.
Inheritance Syntax
class 派生类名(基类名)
...
Some features of inheritance in Python:
- 1. If a subclass needs the parent class's constructor, it must explicitly call the parent class's constructor, or not override the parent class's constructor. For details, see:Notes on Python subclass inheriting parent class constructors.
- 2. When calling a base class method, you need to prefix it with the base class name and include the self parameter. The difference is that when calling a normal function within a class, you do not need to include the self parameter.
- 3. Python always looks for a method of the corresponding type first. If it cannot find the method in the derived class, it then starts searching the base classes one by one. (It first looks for the method to call in the current class; only if it cannot find it does it go to the base classes.)
If more than one class is listed in the inheritance tuple, it is called 'multiple inheritance'.
Syntax:
The declaration of a derived class is similar to that of its parent classes, with the list of inherited base classes following the class name, as follows:
class SubClassName (ParentClass1[, ParentClass2, ...]):
...
Example
#!/usr/bin/python
-- coding: UTF-8 --
class
Parent
:
Define the parent class
parentAttr
=
100
def
init
(
self
)
:
"
Call the parent class constructor
"
def
parentMethod
(
self
)
:
'
Call the parent class method
'
def
setAttr
(
self
,
attr
)
:
Parent
.
parentAttr
=
attr
def
getAttr
(
self
)
:
"
Parent class attributes:
"
,
Parent
.
parentAttr
class
Child
(
Parent
)
:
Define the subclass
def
init
(
self
)
:
"
Call the subclass constructor
"
def
childMethod
(
self
)
:
'
Call the subclass method
'
c
=
Child
(
)
Instantiate the subclasses
c
.
childMethod
(
)
Call the subclass's method
c
.
parentMethod
(
)
Call the parent class method
c
.
setAttr
(
200
)
Call the parent class's method again - set attribute values
c
.
getAttr
(
)
Call the parent class's method again - get attribute values
The result of executing the above code is as follows:
调用子类构造方法
调用子类方法
调用父类方法
父类属性 : 200
You can inherit from multiple classes
class A: # 定义类 A
.....
class B: # 定义类 B
.....
class C(A, B): # 继承类 A 和 B
.....
You can use the issubclass() or isinstance() methods to check.
- issubclass() - a Boolean function that determines whether a class is a subclass or descendant of another class. Syntax: issubclass(sub,sup)
- isinstance(obj, Class) is a Boolean function that returns true if obj is an instance of Class or of a subclass of Class.
Method Overriding
If the functionality of a parent class method does not meet your needs, you can override the parent class's method in the subclass:
Example:
Example
#!/usr/bin/python
-- coding: UTF-8 --
class
Parent
:
Define the parent class
def
myMethod
(
self
)
:
'
Call the parent class method
'
class
Child
(
Parent
)
:
Define the subclass
def
myMethod
(
self
)
:
'
Call the subclass method
'
c
=
Child
(
)
Subclass instance
c
.
myMethod
(
)
The subclass calls the overridden method
The output of executing the above code is as follows:
调用子类方法
Basic Overloading Methods
The following table lists some common functions that you can override in your own classes:
| No. | Method, Description & Simple Call |
|---|---|
| 1 | init ( self [,args...] ) |
构造函数
简单的调用方法: *obj = className(args)* |
| 2 | del( self )
Destructor method, deletes an object
Simple call method: del obj | | 3 | repr( self )
Convert to a form readable by the interpreter
Simple call method: repr(obj) | | 4 | str( self )
Convert a value into a human-readable form
Simple call method: str(obj) | | 5 | cmp ( self, x )
Object comparison
Simple call method: cmp(obj, x) |
operator overloading
Python also supports operator overloading, as in the following example:
Example
#!/usr/bin/python
class
Vector
:
def
init
(
self
,
a
,
b
)
:
self
.
a
=
a
self
.
b
=
b
def
str
(
self
)
:
return
'
Vector (%d, %d)
'
%
(
self
.
a
,
self
.
b
)
def
add
(
self
,
other
)
:
return
Vector
(
self
.
a
other
.
a
,
self
.
b
other
.
b
)
v1
=
Vector
(
2
,
10
)
v2
=
Vector
(
5
,-
2
)
v1
v2
The code above produces the following result:
Vector(7,8)
Class attributes and methods
Private attributes of a class
__private_attrs: starting with two underscores declares the attribute private, so it cannot be used or accessed directly outside the class. When used inside a class method self.__private_attrs.
Class methods
Inside a class, you can define a method for the class using the def keyword. Unlike a normal function definition, a class method must include the parameter self as its first parameter.
Private methods of a class
__private_method: Starting with two underscores declares the method as private, so it cannot be called from outside the class. It can be called inside the class self.__private_methods
Example
#!/usr/bin/python
-- coding: UTF-8 --
class
JustCounter
:
__secretCount
=
0
Private variable
publicCount
=
0
Public variable
def
count
(
self
)
:
self
.
__secretCount
+=
1
self
.
publicCount
+=
1
self
.
__secretCount
counter
=
JustCounter
(
)
counter
.
count
(
)
counter
.
count
(
)
counter
.
publicCount
counter
.
__secretCount
Error: an instance cannot access a private variable
Python includes the class name by changing the name:
1
2
2
Traceback (most recent call last):
File "test.py", line 17, in
print counter.__secretCount # 报错,实例不能访问私有变量
AttributeError: JustCounter instance has no attribute '__secretCount'
Python does not allow instantiated classes to access private data, but you can use object._className__attrName ( objectName._ClassName__privateAttributeName ) to access the attribute. See the following example:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Runoob:
__site = "www.runoob.com"
runoob = Runoob()
print runoob._Runoob__site
After executing the above code, the result is as follows:
www.runoob.com
Explanation of single underscores, double underscores, and leading-and-trailing double underscores:
-
__foo__: Defines special methods, generally names defined by the system, such as __init__() and the like.
-
_foo: A single leading underscore indicates a protected type of variable, meaning that a protected type can only be accessed by itself and its subclasses, and cannot be used for from module import *
-
__foo: A double underscore indicates a private type (private) variable, which can only be accessed by the class itself.