Python3 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.
- **Method:** a function defined inside 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 member:** class variables or instance variables used to hold 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 variable:** in a class declaration, attributes are represented by variables, which are called instance variables; an instance variable is a variable qualified with self.
- **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.
- **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.
Compared with other programming languages, Python added a class mechanism while introducing as little new syntax and semantics as possible.
Classes in Python provide all the basic features of object-oriented programming: the class inheritance mechanism allows multiple base classes, derived classes can override any method of a base class, and a method can call the method of the same name in the base class.
An object can contain any amount and type of data.
Class definition
The syntax format is as follows:
class
ClassName
: <
statement
1
. . . <
statement
N
After a class is instantiated, its attributes can be used; in fact, once a class is created, its attributes can be accessed through the class name.
Class objects
Class objects support two operations: attribute reference and instantiation.
Attribute references use the same standard syntax as all attribute references in Python:obj.name。
After a class object is created, all names in the class namespace are valid attribute names. So if a class definition looks like this:
Example (Python 3.0+)
#!/usr/bin/python3
class
MyClass
:
"""
A simple class example
"""
i
=
12345
def
f
(
self
)
:
return
'
hello world
'
Instantiate the class
x
=
MyClass
(
)
Access the class's attributes and methods
(
"
The attribute i of class MyClass is:
"
,
x
.
i
)
(
"
The method f of class MyClass outputs:
"
,
x
.
f
(
)
)
The above creates a new class instance and assigns the object to the local variable x; x is an empty object.
The output of the above program is:
MyClass 类的属性 i 为: 12345
MyClass 类的方法 f 输出为: hello world
A class has a special method named init() (Constructor), which is called automatically when the class is instantiated, as shown below:
def
init
(
self
)
:
self
.
data
=
[
]
The class defines the init() method; instantiating the class automatically calls the init() method. When class MyClass is instantiated as follows, the corresponding init() method is called:
x = MyClass()
Of course, the init() method can take parameters, passed through init() to the class instantiation operation. For example:
Example (Python 3.0+)
#!/usr/bin/python3
class
Complex
:
def
init
(
self
,
realpart
,
imagpart
)
:
self
.
r
=
realpart
self
.
i
=
imagpart
x
=
Complex
(
3.0
, -
4.5
)
(
x
.
r
,
x
.
i
)
Output: 3.0 -4.5
self represents an instance of the class, not the class
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 0x100771878>
__main__.Test
From the execution result it is clear that self represents the instance of the class, 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:
class
Test
:
def
prt
(
runoob
)
:
(
runoob
)
(
runoob
.
class
)
t
=
Test
(
)
t
.
prt
(
)
The example above produces:
<__main__.Test instance at 0x100771878>
__main__.Test
In Python, self is a conventional name used to refer to the instance (object) of the class itself. It is a reference to the instance that allows class methods to access and manipulate the instance's attributes.
When you define a class and define methods in it, the first parameter is usually named self; you can use another name, but using self is strongly recommended to keep code consistent and readable.
Example
class
MyClass:
def
init
(
self
,
value
)
:
self
.
value
=
value
def
display_value
(
self
)
:
(
self
.
value
)
Create an instance of the class
obj
=
MyClass
(
42
)
Call the instance's method
obj.
display_value
(
)
Outputs 42
In the example above, self is a reference to the class instance; it is used in the init constructor to initialize the instance's attributes, and in the display_value method to access the instance's attributes. By using self, you can access and manipulate the instance's attributes inside class methods, thereby implementing the class's behavior.
Class methods
Inside a class, use the def keyword to define a method; unlike a normal function definition, a class method must include the parameter self as its first parameter, and self represents the instance of the class.
Example (Python 3.0+)
#!/usr/bin/python3
#Class definition
class
people
:
#Define basic attributes
name
=
'
'
age
=
0
#Define private attributes; private attributes cannot be accessed directly from outside the class
__weight
=
0
#Define the constructor
def
init
(
self
,
n
,
a
,
w
)
:
self
.
name
=
n
self
.
age
=
a
self
.
__weight
=
w
def
speak
(
self
)
:
(
"
%s says: I am %d years old.
"
%
(
self
.
name
,
self
.
age
)
)
Instantiate the class
p
=
people
(
'
runoob
'
,
10
,
30
)
p
.
speak
(
)
The output of the above program is:
runoob 说: 我 10 岁。
inheritance
Python also supports class inheritance; if a language does not support inheritance, classes are of little use. A derived class is defined as follows:
class
DerivedClassName
(
BaseClassName
)
: <
statement
1
. . . <
statement
N
A subclass (derived class DerivedClassName) inherits the attributes and methods of its parent (base class BaseClassName).
BaseClassName (the base class name in the instance) must be in the same scope as the derived class definition. Besides a class, an expression can also be used, which is very useful when the base class is defined in another module:
class DerivedClassName(modname.BaseClassName):
Example (Python 3.0+)
#!/usr/bin/python3
#Class definition
class
people
:
#Define basic attributes
name
=
'
'
age
=
0
#Define private attributes; private attributes cannot be accessed directly from outside the class
__weight
=
0
#Define the constructor
def
init
(
self
,
n
,
a
,
w
)
:
self
.
name
=
n
self
.
age
=
a
self
.
__weight
=
w
def
speak
(
self
)
:
(
"
%s says: I am %d years old.
"
%
(
self
.
name
,
self
.
age
)
)
#Single inheritance example
class
student
(
people
)
:
grade
=
'
'
def
init
(
self
,
n
,
a
,
w
,
g
)
:
#Call the parent class constructor
people
.
init
(
self
,
n
,
a
,
w
)
self
.
grade
=
g
#Override the parent class method
def
speak
(
self
)
:
(
"
%s says: I am %d years old and I am in grade %d
"
%
(
self
.
name
,
self
.
age
,
self
.
grade
)
)
s
=
student
(
'
ken
'
,
10
,
60
,
3
)
s
.
speak
(
)
The output of the above program is:
ken 说: 我 10 岁了,我在读 3 年级
Multiple inheritance
Python also has limited support for multiple inheritance. A multiple-inheritance class definition looks like the following example:
class
DerivedClassName
(
Base1
,
Base2
,
Base3
)
: <
statement
1
. . . <
statement
N
Note the order of parent classes in the parentheses: if parent classes have a method with the same name and it is not specified when used in the subclass, Python searches from left to right; that is, when the method is not found in the subclass, it looks from left to right for the method in the parent classes.
Example (Python 3.0+)
#!/usr/bin/python3
#Class definition
class
people
:
#Define basic attributes
name
=
'
'
age
=
0
#Define private attributes; private attributes cannot be accessed directly from outside the class
__weight
=
0
#Define the constructor
def
init
(
self
,
n
,
a
,
w
)
:
self
.
name
=
n
self
.
age
=
a
self
.
__weight
=
w
def
speak
(
self
)
:
(
"
%s says: I am %d years old.
"
%
(
self
.
name
,
self
.
age
)
)
#Single inheritance example
class
student
(
people
)
:
grade
=
'
'
def
init
(
self
,
n
,
a
,
w
,
g
)
:
#Call the parent class constructor
people
.
init
(
self
,
n
,
a
,
w
)
self
.
grade
=
g
#Override the parent class method
def
speak
(
self
)
:
(
"
%s says: I am %d years old and I am in grade %d
"
%
(
self
.
name
,
self
.
age
,
self
.
grade
)
)
#Another class, preparation before multiple inheritance
class
speaker
(
)
:
topic
=
'
'
name
=
'
'
def
init
(
self
,
n
,
t
)
:
self
.
name
=
n
self
.
topic
=
t
def
speak
(
self
)
:
(
"
My name is %s, I am a speaker, and the topic of my speech is %s
"
%
(
self
.
name
,
self
.
topic
)
)
#Multiple inheritance
class
sample
(
speaker
,
student
)
:
a
=
'
'
def
init
(
self
,
n
,
a
,
w
,
g
,
t
)
:
student
.
init
(
self
,
n
,
a
,
w
,
g
)
speaker
.
init
(
self
,
n
,
t
)
test
=
sample
(
"
Tim
"
,
25
,
80
,
4
,
"
Python
"
)
test
.
speak
(
)
#Same method name; by default the method of the parent class listed first in the parentheses is called
The output of the above program is:
我叫 Tim,我是一个演说家,我演讲的主题是 Python
Method Overriding
If the functionality of your parent class's method does not meet your needs, you can override the parent class's method in the subclass, as shown below:
Example (Python 3.0+)
#!/usr/bin/python3
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
super
(
Child
,
c
)
.
myMethod
(
)
#Use the subclass object to call the overridden method of the parent class
The super() functionis a method used to call the parent class (superclass).
The output of the above program is:
调用子类方法
调用父类方法
More documentation:
Notes on Python subclasses inheriting the parent class constructor
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, use the def keyword to define a method; unlike a normal function definition, a class method must include the parameter self as its first parameter, and self represents the instance of the class.
The name self is not fixed; this can also be used, but it is best to follow the convention and use self.
Private methods of a class
__private_method: starting with two underscores declares the method private, so it can only be called inside the class and cannot be called from outside.self.__private_methods。
Example
An example of a class's private attributes:
Example (Python 3.0+)
#!/usr/bin/python3
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
The output of the above program is:
1
2
2
Traceback (most recent call last):
File "test.py", line 16, in
print (counter.__secretCount) # 报错,实例不能访问私有变量
AttributeError: 'JustCounter' object has no attribute '__secretCount'
An example of a class's private methods:
Example (Python 3.0+)
#!/usr/bin/python3
class
Site
:
def
init
(
self
,
name
,
url
)
:
self
.
name
=
name
public
self
.
__url
=
url
private
def
who
(
self
)
:
(
'
name :
'
,
self
.
name
)
(
'
url :
'
,
self
.
__url
)
def
__foo
(
self
)
:
Private methods
(
'
This is a private method
'
)
def
foo
(
self
)
:
Public method
(
'
This is a public method
'
)
self
.
__foo
(
)
x
=
Site
(
'
Runoob Tutorial
'
,
'
www.runoob.com
'
)
x
.
who
(
)
Normal output
x
.
foo
(
)
Normal output
x
.
__foo
(
)
Error
The example above produces:

Special methods of a class:
- init : Constructor, called when the object is created
- del : Destructor, used when the object is released
- repr : Printing, conversion
- setitem : Assignment by index
- getitem: Getting a value by index
- len: Getting the length
- cmp: Comparison operations
- call: Function call
- add: Addition
- sub: Subtraction
- mul: Multiplication
- truediv: Division
- mod: Modulo operation
- pow: Exponentiation
operator overloading
Python also supports operator overloading; we can override a class's special methods, as shown below:
Example (Python 3.0+)
#!/usr/bin/python3
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)