Python Advanced-03 object-oriented Programming

Source: Internet
Author: User
Tags instance method uppercase letter

1. Defining a Class 1.1 definition

In Python, classes are defined by the class keyword.

According to Python's programming habits, the class name begins with an uppercase letter , followed by (object), indicating which class the class inherits from.

class Person (object):

Pass

1.2 Instance Creation

Creating an instance is created using the class name + (), like a function call.

Xiaoming = person ()

Xiaohong = person ()

2 Property 2.1 Adding instance Properties

Since Python is a dynamic language, for each instance, it is possible to assign values directly to their properties, which do not have to be declared in the class.

class Person (object):

Pass

P1 = person ()

P1.name = ' Bart '

P2 = person ()

P2.name = ' Adam '

P3 = person ()

P3.name = ' Lisa '

2.2. Initializing Instance Properties

While we are free to bind various properties to an instance, in the real world, an instance of a type should have properties of the same name.

When defining the person class, you can add a special __init__ () method to the person class, and when the instance is created, the __init__ () method is automatically called , and we can add a uniform attribute to each instance here .

Example

class Person (object):

def __init__ (self, name, gender, birth):

Self.name = Name

Self.gender = Gender

Self.birth = Birth

2.3. Internal properties (private property) implementation

If an attribute starts with a double underscore (__), the property cannot be accessed externally .

However, if a property is defined as "__xxx__", then it can be accessed externally , the properties defined with "__xxx__" are called special properties in the Python class, there are many predefined special properties that can be used, and usually we do not use the normal attribute "__ xxx__ "Definition.

An attribute "_xxx" that begins with a single underscore can also be accessed externally.

Important: Even if the private property has the same name as the property later bound by the instance, and the property of the subsequent instance is changed, the private property will not change.

>>> class Test_c (object):

def __init__ (self):

self.__test=3

def get_test_a (self):

Return self.__test

Test_a=property (get_test_a)

@property

def test_b (self):

Return "BBB"

>>> A=test_c ()

>>> a.test_a

3

>>> a.__test=5

>>> a.test_a

3

2.4 Class attribute 2.4.1 Concept

Binding a property on a class, all instances have access to the properties of the class, and the class properties accessed by all instances are the same! That is, instance properties each have each instance owned and independent of each other, and the class attribute has only one copy.

2.4.2 Features

Because Python is a dynamic language, class properties can be added and modified dynamically .

because the class attribute has only one copy , when the address of the person class changes, the class properties accessed by all instances change.

2.4.3 definition

Defining class properties can be defined directly in class:

#给 the person class adds a class property count, with each instance created, adds 1 to the Count property, so that you can count the instances of how many of the person were created altogether.

class Person (object):

Count=0

def __init__ (self,name):

Person.count+=1

Self.name=name

2.4.4 class attributes conflict with instance properties

When instance properties and class attributes have the same name, the instance property has a high precedence , which masks access to the class properties.

Using an instance to modify a class property is an error because your modification is equivalent to binding an instance property to an instance, and does not change the value of the Class property.

class Person (object):

Address = ' Earth '

def __init__ (self, name):

Self.name = Name

P1 = person (' Bob ')

P2 = person (' Alice ')

print ' person.address = ' + person.address

p1.address = ' China '

print ' p1.address = ' + p1.address

print ' person.address = ' + person.address

print ' p2.address = ' + p2.address

__xx of 2.4.5 class properties

Directly using the class name. __ Class Property name Access cannot access the

Use the class object. _ Class Name __ Class property name to access the

3. Method 3.1 Instance method

Defined

An instance is a function defined in a class whose first argument is always self, pointing to the instance itself that invokes the method, and the other parameters are exactly the same as a normal function.

Def instance method name (self, parameter 1, parameter 2,...):

Method block

Call

instance. The instance method name (parameter 1, parameter 2,...) #self不需要显式传入

3.2 Adding a method to an instance dynamically

Because the method is also a property, it can also be dynamically added to the instance ( just added to this instance, not normally ).

Import types

def fn_get_grade (self):

If Self.score >= 80:

Return ' A '

If Self.score >= 60:

Return ' B '

Return ' C '

class Person (object):

def __init__ (self, Name, score):

Self.name = Name

Self.score = Score

P1 = person (' Bob ', 90)

P1.get_grade = types. Methodtype (Fn_get_grade, p1, person)

Print P1.get_grade ()

# = A

P2 = person (' Alice ', 65)

Print P2.get_grade ()

# error:attributeerror: ' Person ' object with no attribute ' Get_grade '

# because the P2 instance is not bound Get_grade

3.3 class Method 3.3.1 Definition

By marking a @classmethod, the method binds to the person class, not to an instance of the class;

The first parameter of the class method passes into the class itself, typically naming the parameter name CLS;

3.3.2 Features

Because it is called on the class, not on the instance, the class method cannot get any instance variables , only the reference to the class is obtained. class methods are typically used to handle internal class variables.

3.3.3 Example

The following cls.count are actually equivalent to Person.count.

class Person (object):

__count = 0

@classmethod

def how_many (CLS):

Return Cls.__count

def __init__ (self,name):

Self.name=name

Person.__count +=1

Print Person.how_many ()

P1 = person (' Bob ')

Print Person.how_many ()

4. Inheritance 4.1 definition

New classes don't have to be written

The new class inherits from the existing class and automatically has all the functionality of the existing class

New classes only need to write functionality that is missing from existing classes

Parent class/base class/Superclass---subclass/derived class/inheriting class

4.2 Advantages

Reusing existing code

Automatically owns all the features of an existing class

Just write the missing new features

4.3 features

Subclass is a parent class (student is a person)

Any class of python must inherit from a class

Don't forget to call Super (subclass,self). __init__ (*args) # args can no longer write self

4.4 Examples

class Person (object):

def __init__ (self, Name, gender):

Self.name = Name

Self.gender = Gender

Class Teacher (person):

def __init__ (self, name, gender, course):

Super (Teacher,self) __init__ (Name,gender)

Self.course=course

4.5isinstance () Judging type

Can be used to determine whether an object is of a certain type.

Note: An object is a subclass type and must also be the corresponding type of the parent class of the child class.

Isinstance (object, class-or-type-or-tuple), BOOL

# See Python Basics-06 functions

4.6 Multiple Inheritance

The purpose of multiple inheritance is to Select and inherit subclasses from the two inheritance trees, so that the composition function is used .

For example, Python's Web server has TCPServer, Udpserver, Unixstreamserver, Unixdatagramserver, and the server run mode has multiple processes forkingmixin and Multithreading threadingmixin two kinds.

To create a tcpserver for a multi-process pattern:

Class Mytcpserver (TCPServer, Forkingmixin)

Pass

To create a udpserver for multithreaded mode:

Class Myudpserver (Udpserver, ThreadingMixIn):

Pass

If there is no multiple inheritance, the 4x2=8 subclasses are required to implement all the possible combinations above .

5. polymorphic 5.1 Definition

1. Generally (such as in Java), the parent class has a method, its subclasses through different implementations, the implementation of the method, is polymorphic;

2. because Python is a dynamic language, the parameter x passed to the Polymorphic method is not necessarily a parent or base class type. An instance of any data type is possible, as long as it has a method with the same name as the Polymorphic method.

5.2 Principle

1. In general (such as in Java), a method call will work on the actual type of x. S is the student type, which actually has its own WhoAmI () method and the WhoAmI method inherited from person, but calls S.whoami () always finds its own definition, and if not defined, looks up through the inheritance chain until it is found in a parent class;

2. Because Python is a dynamic language, the parameter x passed to the Polymorphic method is not necessarily a parent or base class type. An instance of any data type is possible, as long as it has a method with the same name as the Polymorphic method.

5.3 Polymorphism of Dynamic languages

A dynamic language invokes an instance method, does not check the type, and can be called as long as the method exists and the parameter is correct.

Understand:

Python provides an open () function that opens a disk file and returns a file object. The file object has a read () method to read the contents of the files:

For example, read the contents from a file and parse it into JSON results:

Import JSON

f = open ('/path/to/file.json ', ' R ')

Print Json.load (f)

Due to the dynamic nature of Python, json.load () does not necessarily read content from a file object. Any object, as long as the read () method is called a File-like object, can be passed to Json.load ().

Import JSON

Class Students (object):

def __init__ (self):

Pass

def read (self):

return R ' ["Tim", "Bob", "Alice"] '

s = Students ()

Print Json.load (s)

# result: [u ' Tim ', U ' Bob ', U ' Alice ')

6. Functions commonly used in class 6.1setattr ()

SetAttr (object, name, value)

Used to set the properties of an object, using Help (SetAttr) to view

Python Advanced-03 object-oriented Programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.