Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Object-Oriented Programming

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


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

)

:

print

"

Total Employee %d

"

%

Employee

.

empCount

def

displayEmployee

(

self

)

:

print

"

Name :

"

,

self

.

name

,

"

, Salary:

"

,

self

.

salary

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

)

:

print

(

self

)

print

(

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

)

:

print

(

runoob

)

print

(

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

)

:

print

"

Total Employee %d

"

%

Employee

.

empCount

def

displayEmployee

(

self

)

:

print

"

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

(

)

print

"

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:

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

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

)

:

print

"

Total Employee %d

"

%

Employee

.

empCount

def

displayEmployee

(

self

)

:

print

"

Name :

"

,

self

.

name

,

"

, Salary:

"

,

self

.

salary

print

"

Employee.doc:

"

,

Employee

.

doc

print

"

Employee.name:

"

,

Employee

.

name

print

"

Employee.module:

"

,

Employee

.

module

print

"

Employee.bases:

"

,

Employee

.

bases

print

"

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

print

class_name

,

"

Destroy

"

pt1

=

Point

(

)

pt2

=

pt1

pt3

=

pt1

print

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:

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

)

:

print

"

Call the parent class constructor

"

def

parentMethod

(

self

)

:

print

'

Call the parent class method

'

def

setAttr

(

self

,

attr

)

:

Parent

.

parentAttr

=

attr

def

getAttr

(

self

)

:

print

"

Parent class attributes:

"

,

Parent

.

parentAttr

class

Child

(

Parent

)

:

Define the subclass

def

init

(

self

)

:

print

"

Call the subclass constructor

"

def

childMethod

(

self

)

:

print

'

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.


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

)

:

print

'

Call the parent class method

'

class

Child

(

Parent

)

:

Define the subclass

def

myMethod

(

self

)

:

print

'

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

)

print

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

print

self

.

__secretCount

counter

=

JustCounter

(

)

counter

.

count

(

)

counter

.

count

(

)

print

counter

.

publicCount

print

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: