Python notes-Object-oriented

Source: Internet
Author: User

Object-Oriented Programming

Object-oriented programming is a programmatic approach that requires the use of "classes" and "objects" to implement:

A class is a template, a template can contain multiple functions, function to implement some functions, to achieve a common feature of the description of things;

An object is an entity of a class and is a data type. It does not exist in memory and cannot be manipulated directly, but only when the object is instantiated. To illustrate:

#!/usr/bin/env python# -*- coding:utf-8 -*-class The  student ():     #calss是关键字, which indicates that the class Student is the name of the class, usually capitalized in the first letter. s=100                #类属性, which belongs to the global variable. "This is a test class # to add a comment to the class '     def name (self,name):     #类中的函数, The first argument must be self.         print  ' i am %s '%namedef score (self):p rint  self.s                # Method calls the Class Property obj=student ()                  #obj就是对象的实例化, you can use Tyte (obj) to view its type. Obj.name (' Zhangsan ')          #调用类的方法, Output is "I am zhangsan" 

First, __init__ Initializing instance properties

Python defines a __init__ method that initializes class variables, passes the parameters of a class, for example:

#初始化类变量

#!/usr/bin/env python#-*-coding:utf-8-*-class Student (): Def __init__ (self): #__init__函数定义到类的开头 SELF.N        Ame= ' Zhangsan ' #初始化变量, which can be called in a later function. self.score=100 def print_score (self): print '%s:%s '% (self.name,self.score) #调用self. Namef=student () F.print_sco Re ()

Note: The Self.name variable is an instance property that can only be used in a class method.

#传参

#!/usr/bin/env python#-*-coding:utf-8-*-class Student (): Def __init__ (self,a,b): Self.name=a #初始化变量, just given        is not a fixed value, it is a mutable parameter. Self.score=b def print_score (self): print '%s:%s '% (self.name,self.score) f=student (' Zhangsan ', ' + ') #定义参数, passed to __init__ function F.print_score ()

Note: We do not specifically call the __init__ method, but when creating a new instance of a class, include the parameters in parentheses followed by the class name, which is passed to the __init__ method.

Second, Private Properties

A variable that begins with a double underscore, which represents a private variable, is protected, can only be accessed by the class itself, and cannot be accessed by a subclass, for example:

#!/usr/bin/env Pythonclass Info (): Def __init__ (self): Self.__name= ' Zhangsan ' def say (self): print sel F__namea=info () Print A.__name

executing the above code will cause an error: Attributeerror:info instance has no attribute ' __name '

In fact, this is a pseudo-private, for example:

#!/usr/bin/env Pythonclass Info (): Def __init__ (self): Self.__name= ' Zhangsan ' def say (self): print sel F__namea=info () Print A._info__name #在属性前面加上_classname依然可以打印出来

Note: The class method name in Python that begins with a double-dip, is automatically conceptually after the class instantiation, and _classname in front of its name, because the name is changed, so nature cannot be accessed with the name of the double-dip start, thus achieving the non-entry purpose.

For a detailed description of the private property, refer to:

http://blog.itpub.net/26250550/viewspace-1411768/

Third, three main features of object-oriented

1. Encapsulation

From the above example, you can see that object-oriented programming requires two steps:

(1) encapsulate the content somewhere

By creating a class, instantiating an object, you actually encapsulate the content in the object.

(2) calling the encapsulated content from somewhere

There are two general scenarios for invoking the encapsulated content:

#通过对象直接调用 (first example)

Indirect invocation of #通过 self (second example)

2. Inheritance

Subclasses inherit the properties and methods of the parent class, which can improve code reuse.

# Simple Inheritance

#!/usr/bin/env Pythonclass Student (): Def __init__ (self,a,b): Self.name=a self.score=b def Print_score  (self): print '%s:%s '% (Self.name,self.score) class One (Student): #子类: One, parent class: Student passf=one (' Zhangsan ', +) print f.name# calls the parent class's property F.print_score () #调用父类的方法 # The output is as follows: zhangsanzhangsan:100

# Subclass Instance Initialization

If the subclass instance property is initialized, the properties and methods of the parent class are not inherited:

#!/usr/bin/env Pythonclass Boy (): Def __init__ (self): self.sex= ' boy ' self.height= ' the "Def Print_mes (s ELF): print ' sex:%s,hei:%s '% (Self.sex,self.height) class Name (boy): Def __init__ (self): #子类初始化实例属性 self . Name= ' Zhangsan ' def print_name (self): print ' name:%s '%self.namef=name () print f.namef.print_name () f.print_mes () # The exception information is as follows: attributeerror:name instance has no attribute ' sex '

The attribute in the parent class was not found, stating that the methods in the parent class were not inherited by the quilt class.

Workaround One:

#!/usr/bin/env Pythonclass Boy (): Def __init__ (self): self.sex= ' boy ' self.height= ' the "Def Print_mes (s     ELF): print ' sex:%s,hei:%s '% (Self.sex,self.height) class Name (boy): Def __init__ (self): boy.__init__ (self) #将父类的__init__方法添加到子类中 self.name= ' Zhangsan ' def print_name (self): print ' name:%s '%self.namef=name () pri NT F.namef.print_name () F.print_mes ()

Workaround Two:

#!/usr/bin/env Pythonclass Boy (object): #需要指定基类object (New Class) def __init__ (self): self.sex= ' Boy ' Self.hei Ght= ' Print_mes ' def: print ' sex:%s,hei:%s '% (Self.sex,self.height) class Name (boy): Def __init__ (self        ): Super (Name, self). __init__ () #使用super函数 (super can only be used in modern classes) Self.name= ' Zhangsan ' def print_name (self): print ' name:%s '%self.namef=name () print f.namef.print_name () f.print_mes ()

# Multiple Inheritance

a subclass has more than one parent class, and if the property or method that is called does not appear in the subclass, it is looked up from the parent class. In classic and modern classes, lookups differ in the way they are found. python3.0 is no longer classic class, unified as a new class.

Classic class:

By default, there is no parent class, and multiple inheritance cases are looked up in depth first.

New class:

There are inherited classes, and if not, you can inherit object. In multiple inheritance cases, the breadth-first method is searched.

To illustrate:

Class D: #经典类 def bar (self): print ' D.bar ' class C (d): Def Bar (self): print ' C.bar ' class B (d): de F Bar (self): print ' B.bar ' class A (B, C): Def bar (self): print ' a.bar ' a = A () A.bar ()

When executing the Bar method:

First go to a class to find, if not in class a , then continue to the class B to find, if not in class B , then continue to the class D , if there is a class D , then continue to C class, or if it is not found, an error.

So, look in order: A-and B--and D-and C

In the process of finding the bar method above, once found, the search process is immediately interrupted and no further search is made.

Class D (object): #新式类 def Bar (self): print ' D.bar ' class C (d): Def Bar (self): print ' C.bar ' class B (d ): Def bar (self): print ' B.bar ' class A (B, C): Def bar (self): print ' a.bar ' a = A () A.bar ()

When executing the Bar method:

First go to a class to find, if not in class a , then continue to the class B to find, if not in class B , then continue to the class C , if there is a class C , then continue to D class, or if it is not found, an error.

So, look in order: A--B--and C--D

In the process of finding the bar method above, once found, the search process is immediately interrupted and no further search is made.

# polymorphic

Class F1:passclass S1 (F1): Def show (self): print ' S1.show ' class S2 (F1): Def show (self): print ' S2. Show ' Def Func (obj): Print obj.show () S1_obj = S1 () func (s1_obj) s2_obj = S2 () func (s2_obj) #为了让Func函数既可以执行S1对象的show方法 and can be The S2 object's Show method, so that a parent class of S1 and S2 classes is defined, and the actual parameters passed in are: S1 object and S2 object.

As can be seen from the above example, the same message may be sent to a number of different objects, and the system can be based on the object belongs to the class, the corresponding class of methods, and have different behavior, this is the characteristics of polymorphism.


This article is from the "Network Technology" blog, please be sure to keep this source http://fengjicheng.blog.51cto.com/11891287/1930542

Python notes-Object-oriented

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.