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

Python3 Object-Oriented Programming

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

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

print

(

"

The attribute i of class MyClass is:

"

,

x

.

i

)

print

(

"

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

)

print

(

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

)

:

print

(

self

)

print

(

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

)

:

print

(

runoob

)

print

(

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

)

:

       

print

(

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

)

:

print

(

"

%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

)

:

print

(

"

%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

)

:

print

(

"

%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

)

:

print

(

"

%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

)

:

print

(

"

%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

)

:

print

(

"

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

)

:

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

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

print

(

self

.

__secretCount

)

counter

=

JustCounter

(

)

counter

.

count

(

)

counter

.

count

(

)

print

(

counter

.

publicCount

)

print

(

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

)

:

print

(

'

name :

'

,

self

.

name

)

print

(

'

url :

'

,

self

.

__url

)

def

__foo

(

self

)

:

Private methods

print

(

'

This is a private method

'

)

def

foo

(

self

)

:

Public method

print

(

'

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:

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

)

print

(

v1

v2

)

The code above produces the following result:


Vector(7,8)