Home > Backend Development > Python Tutorial > Python learning object-oriented programming characteristics (2)

Python learning object-oriented programming characteristics (2)

巴扎黑
Release: 2017-04-01 13:34:53
Original
1411 people have browsed it

The term object (Object) in object-oriented programming can basically be regarded as a collection of data (properties) and a series of methods that can access and operate these data. In the traditional sense, "program = data structure + algorithm" is encapsulated, "covered up" and simplified to "program = object + message". Objects are instances of classes, and the abstraction of classes needs to be encapsulated. Encapsulation allows the caller to use the object directly without caring about how the object is constructed.

First explain the python programming specifications:

#!/usr/bin/env python
#coding=utf-8
#编程规范,示例如下:
 
class ClassName(object):
       '''testdoc         #这里面是一些说明文档,该类的说明信息是可以被help看到的
              example:
       '''
       #注释的写法,可以在后面,也可以在上一行,单行注释以#号开头
       a= 100          #this is a number for a
       #thisis a number for b
       b= 200
       c= ['a','b']   #or 分行写
       d= {                                   #列表、字典等可以分行写,这样更加直观
                     'key1':'v1',
                     'key2':'v2',
                     'key3':'v3'
       }
 
       def__init__(self,num,m):                   #初始化方法。如果不写,则是从基类继承
              self.age= num
              self.__money= m
 
       deftest(self):
              return100
 
       def__eq__(self,other):                 #魔术方法
              returnself.age == other.age
 
       def__del__(self):   #析构函数,在整个类调用执行完后会执行
              print'world'
 
d = Hello(2,200)
d2 = Hello(3,100)
 
print d == d2         #会自动调用__eq__方法,返回比较结果
 
print d
print d2
Copy after login



Writing specifications generally include explanatory text, initialization method, single-line or multi-line comments, etc.

1. Construction method:

The following example illustrates the execution sequence of the construction method and initialization method:

#!/usr/bin/env python
 
class Of(object):
 
       def __new__(cls,*args,**kwargs):               #构造方法
                print 'new'
                return super(Of,cls).__new__(cls,*args,**kwargs)
                #returnobject.__new__(cls,*args,**kwargs)
 
       def __init__(self):                #初始化方法
                print "init"
 
       def test(self):
                print 'hello'
 
f = Of()
Copy after login

The execution results are as follows:

new
init
Copy after login

It shows that when a class is instantiated, it will first execute the constructor method, and then execute the initialization method

The following example illustrates the difference between the constructor method and the initialization method:

#!/usr/bin/env python
 
class Resource(object):                 #父类的定义
       def __init__(self):                #初始化方法,为了说明这里直接输出名字
                print 'call me resource init'
 
       def __new__(cls,*args,**kwargs):               #构造方法,这里使用这种传参可以接受任何类型的参数
                print "resource new"
                returnobject.__new__(cls,*args,**kwargs)         #返回值为object基类的构造方法的返回值
 
class DockerResource(Resource):         #子类的定义,继承了Resource类
       def __new__(cls,*args,**kwargs):               #重新构造自己的构造方法
                print "call me dockerresource new"
                returnResource.__new__(cls,*args,**kwargs)            #返回值为Resource父类的构造方法的返回值
 
 
       def __init__(self):                #定义自己的初始化方法
                print 'call docker resourceinit'
 
       def test(self):                #定义test方法
                print 'dosker resource test'
 
r = DockerResource()                  #实例化DockerResource,并将返回值传递给r
print r                          #打印r,查看返回值是什么
print type(r)                  #查看r的类型
r.test()
Copy after login

The output results are as follows:

call me docker resource new                #首先调用了DockerResource的构造方法
resource new                                      #构造方法返回的是Resource的构造方法,所以会执行Resource父类构造方法的print "resource new"
call docker resource init                      #然后会执行自己的初始化方法
<__main__.DockerResource object at0x7fa1a3edcf90>             #r现在接受的是Resource父类的构造方法的返回值,所以会有object出现
<class &#39;__main__.DockerResource&#39;>                    #类型为自己DockerResource
dosker resource test                                   #调用自己的test方法
Copy after login

In the class, it will first execute its own construction method. If not, it will inherit from the parent class, and then execute its own initialization method. If not, it will still be inherited from the parent class, and then you can call your own instance method normally


2. Inheritance:
The following example illustrates subclass inheritance The execution result of the parent class

#!/usr/bin/env python
 
class Resource(object):                 #定义一个父类,继承于object基类
 
       def __new__(cls,*args,**kwargs):        #构造方法
                print &#39;class resource __new__&#39;
                obj =super(Resource,cls).__new__(cls,*args,**kwargs)            #利用super函数找到自己的父类,并将它的构造方法传递给obj
                print obj.__class__        #打印obj的类型
                return obj                     #返回值为obj
 
       def __init__(self):                       #初始化方法
                print "call me init forResource"
 
       def test(self):
                print "call me test forResource"
 
       def create(self):
                print "call me create forResource"
 
class subResource(Resource):               #定义子类,继承Resource父类
 
       def __init__(self):                #定义自己的初始化方法
                print &#39;sub resource init&#39;
 
       def test(self):
                print &#39;sub resource test&#39;
 
class Heat(object):                #定义一个Heat类,继承于基类object,是个新式类
 
       def __new__(cls,*args,**kwargs):               #定义自己的构造方法
                print "class __new__%s" % cls
                returnobject.__new__(cls,*args,**kwargs)                #返回值为object基类的构造方法的返回值
 
       def __init__(self):                #定义初始化方法
                print &#39;heat init&#39;
 
 
r = Heat()                     #实例化
print r
h = Resource()              #实例化
print h
f = subResource()          #实例化
print f
Copy after login

is as follows:

class __new__ <class &#39;__main__.Heat&#39;>               #实例化Heat类,首先执行自己的构造方法和初始化方法,所以先输出构造方法的print语句
heat init                        #执行了自己的初始化方法
<__main__.Heat object at0x7f43349ac050>                     #r实例化后继承的是object基类,打印返回值
class resource __new__                #实例化Resource类,首先执行自己的构造方法和初始化方法,所以先输出构造方法的print语句
<class &#39;__main__.Resource&#39;>         #打印父类构造方法的返回值的类名
call me init for Resource                     #执行自己的初始化方法
<__main__.Resource object at0x7f43349ac090>               # h实例化后继承的是object基类,打印返回值
 
class resource __new__                #实例化subResource类,首先执行父类的构造方法,所以先输出父类构造方法的print语句
<class &#39;__main__.subResource&#39;>           #父类构造方法里面打印自己的类名
sub resource init                   #执行自己的初始化方法
<__main__.subResource object at0x7f43349ac0d0>                 #f实例化后是执行了父类Resource类的构造方法,返回的依旧是object基类
Copy after login



3. Multiple inheritance:

#!/usr/bin/env python
 
class A(object):
       def __init__(self):
               pass
       def ma(self):
                print &#39;a.ma&#39;
       def m(self):
                print &#39;it is A&#39;
class B(object):
       def mb(self):
                print &#39;b.mb&#39;
       def m(self):
                print &#39;it is B&#39;
 
class C(A,B):
       pass
 
c = C()
c.ma()
c.mb()
c.m()
Copy after login

The execution results are as follows:

a.ma
b.mb
it is A
Copy after login

Through the execution results, we can see that C inherits A and B, so it can call the ma() method of A or B mb() method; but when there are the same methods in A and B, it will give priority to the first inherited super class.

4. Inheritance and overloading:

#!/usr/bin/env python
 
class Phone(object):
 
       def __init__(self,size,color,memory):
                self.size = size
                self.color = color
                self.memory = memory
 
       def call(self):
                s = &#39;I can call&#39;
                return s
       def sms(self):
                s = &#39;Are you gua le mei?&#39;
#!/usr/bin/env python
 
class Phone(object):
 
       def __init__(self,size,color,memory):
                self.size = size
                self.color = color
                self.memory = memory
 
       def call(self):
                s = &#39;I can call&#39;
                return s
       def sms(self):
                s = &#39;Are you gua le mei?&#39;
                return s
 
class Phones(Phone):            #继承了Phone类,重载了自己的初始化方法,又增加了自己的方法,既拥有超类的方法,又有自己特有的方法
 
       def __init__(self,size,color,memory,pix):
                self.pix = pix
               super(Phones,self).__init__(size,color,memory)
 
       def install_app(self,app):
                s = &#39;install %s&#39; % app
                return s
 
class Huwei(Phone):                    #继承了Phone类,又增加了自己的方法,既拥有超类的方法,又有自己特有的方法
 
       def weixin(self,msg):
                if msg.find(&#39;gcd&#39;) == -1:
                        return &#39;sending....&#39;
                else:
                        return &#39;You can\&#39;t sendthe msg&#39;
 
p = Phone(1.2,&#39;black&#39;,&#39;4M&#39;)                  #实例化
 
iphone =Phones(4.7,&#39;white&#39;,&#39;4G&#39;,&#39;1280*766&#39;)        #实例化
 
h = Huwei(4.7,&#39;yellow&#39;,&#39;4G&#39;)                #实例化
 
print iphone.install_app(&#39;weixin&#39;)          #执行特有的install_app方法
 
print h.sms()
print h.call()
print h.weixin(&#39;wansui&#39;)
sms = p.sms()
call = p.call()
print sms,call
Copy after login

The execution results are as follows:

install weixin
Are you gua le mei?
I can call
sending....
Are you gua le mei? I can call
Copy after login

The overloading of the method is actually Use the def keyword in a class to overload the parent class's methods. If you overload a method in the parent class but need to
use the method of the parent class in the class, you can use the parent class name plus '.' plus the method name to call

5 , Magic method:

#!/usr/bin/env python
 
class Information(object):
       &#39;&#39;&#39;This is a doc                #说明文档
                example for test,please don&#39;tchange it.
       &#39;&#39;&#39;
 
       def __init__(self,sch,cla,m,n):             #定义初始化方法
                print "welecome to schoolsystem."
                self.school = sch                   #实例变量
                self.classroom = cla                     #实例变量
                self.num = 100                     #实例变量
                self.__money = m                #私有变量
                self.num = n                        #实例变量
 
       def school_name(self):                 #返回实例变量,即将实例变量传递出去
                return self.school
 
       def class_name(self):                   #返回实例变量,即将实例变量传递出去
                return self.classroom
 
       def class_money(self):                 #返回私有变量,即将私有变量传递出去
                return self.__money
              #魔术方法:以双下划线开头,以双下划线结尾的方法是魔术方法
       def __eq__(self,another):             #当外部出现&#39;==&#39;比较的时候,调用此魔术方法
                return self.__money ==another.__money           #返回两个私有变量的比较结果(布尔值),这里self是&#39;==&#39;左边的参数值,another是右边的参数值
 
       def __gt__(self,another):                     #当外部出现&#39;>&#39;比较的时候,调用此魔术方法
                return self.__money >another.__money             #返回两个私有变量的比较结果(布尔值),这里self是&#39;>&#39;左边的参数值,another是右边的参数值
 
       def __ne__(self,another):             #当外部出现&#39;!=&#39;比较的时候,调用此魔术方法
                return self.__money !=another.__money            #返回两个私有变量的比较结果(布尔值),这里self是&#39;!=&#39;左边的参数值,another是右边的参数值
 
       def __add__(self,another):            #当外部出现&#39;+&#39;运算符的时候,调用此魔术方法
                return self.__money +another.__money      #返回两个私有变量的相加结果,这里self是&#39;!=&#39;左边的参数值,another是右边的参数值
                #returnInformation(&#39;jiaoda&#39;,&#39;dz1302&#39;,self.__money + another.__money)
                #return Information(&#39;jiaoda&#39;,&#39;dz1302&#39;,1024,self.num+ another.num)
 
       def __str__(self):
                return &#39;money = %d&#39; %self.__money
 
       def __hash__(self):               #获取hash值
                return 1314521
 
       def __getattr__(self,name):                  #当调用不存在的方法时,执行此方法进行输出
                print "get attr %s" %name
                return name
 
       def __del__(self):          #析构方法,当不再使用此类时,会自动执行
                print "Goodbye,welecomhere again."
 
f = Information(&#39;youdian&#39;,&#39;tg1312&#39;,9999,6)           #实例化
l = Information(&#39;ligong&#39;,&#39;jk1213&#39;,6666,4)             #实例化
print f == l            #调用魔术方法__eq__()
print f + l                     #调用魔术方法__add__()
print f > l                     #调用魔术方法__gt__()
 
s = f + l                 #
print s
print f.ccc              #名字不存在,调用__getatter__()方法
Copy after login



__str__ is called by the print function, and usually returns something. This thing should be expressed in the form of a string. If not, use the str() function to convert. When you print a class, the first thing print calls is the __str__ defined in the class

The execution result is as follows:

welecome to school system.          #首先会在实例化的时候执行初始化方法
welecome to school system.          #第二次实例化调用初始化方法
False                     #打印__eq__()的返回值为False
16665                   #打印__add__()的返回值为两数相加
True                      #打印__gt__()的返回值为True
16665
get attr ccc             #执行__getattr__()方法
ccc
Goodbye,welecom here again.             #执行完会自动执行析构函数
Goodbye,welecom here again.
Copy after login



6. Modules:
In python, it comes with more than 200 modules. Now, after everyone’s continuous improvement and improvement, the official website has collected more than 2,000 library modules, which can achieve almost any function you want.

When we use it ourselves, we can also use our own module. Any .py can be imported as a separate module;

Now we first define a module of our own: module. py

#!/usr/bin/env python
#coding=utf-8
 
def test():
       print&#39;This is a test&#39;
 
def test2():
       print&#39;test2&#39;
 
class DB(object):
       def__init__(self):
              self.a= 101
       deftest(self):
              returnself.a
Copy after login

In the same directory, open python interactively and you can import this module. The name is the name of the file module;
Write in the file to make the import call,,,,here It is in the same directory (same layer)

#!/usr/bin/env python
 
import module
module.test()
Copy after login

The result is as follows:

This is a test
Copy after login

Improve it and call the class in the module:

#!/usr/bin/env python
 
import module
h = module.DB()
print h.test()
Copy after login

The output results are as follows:

101
Copy after login

Let’s try to import the module in a directory:
Create a new directory heat and write several module files in it
The directory must be Only __init__.py can be imported as a module

Python learning object-oriented programming characteristics (2)


The content of docker.py in the heat directory is:

#!/usr/bin/env python
 
def docker():
       return&#39;This is a docker in heat&#39;
 
class Docker(object):
       defcreate_c(self):
              return&#39;1314521aaa&#39;
 
       defstop_c(self):
              return&#39;it is stop&#39;
 
print __name__
 
if __name__ == &#39;__main__&#39;:
       print__name__
       d= Docker()
Copy after login



The content of nova.py in the heat directory is:

#!/usr/bin/env python
 
def nova():
       return&#39;This is a nova&#39;
 
class Nova(object):
       deftest(self):
              return&#39;This is a test in nova&#39;
Copy after login



Now there is only the file __init__ in the heat directory, and there is no content in the file

Write a calling script file:

#!/usr/bin/env python
#coding=utf-8
 
import heat.docker               #目录下__init__.py里面没有__all__
printheat.docker.docker()
Copy after login

The execution result is as follows:

heat.docker
This is a docker in heat
This is a docker in heat
Copy after login

Now you can only import specific modules in the directory, import them as above and call;

In order to import all module files in the directory, you can add the following content to __init__.py in the directory:

__all__ = [&#39;docker&#39;,&#39;nova&#39;]                    #将所有模块名字写入
Copy after login

Change the executable file Content:

#!/usr/bin/env python
#coding=utf-8
 
import heat.docker               #目录下__init__.py里面没有__all__
print heat.docker.docker()
 
from heat import *               #heat目录下__init__里面内容是:__all__ = [&#39;docker&#39;,nova&#39;]
print docker.docker()
print nova.nova()
n = nova.Nova()
print n.test()
Copy after login

The execution results are as follows:

heat.docker
This is a docker in heat
This is a docker in heat
This is a nova
This is a test in nova
Copy after login

If there are modules that need to be imported in the directory, you can continue to write the __init__.py file in it , and write the name of the module file in the directory, and just add an extra layer of directories when calling.

Python learning object-oriented programming characteristics (2)

The following is an example of the content of the mod.py file:

#!/usr/bin/env python
#coding=utf-8
 
def hello():
       return&#39;hello everyone&#39;
 
class Hello(object):
       def__init__(self):
              self.a= 103
       deftest(self):
              return&#39;This is a test in Hello&#39;
Copy after login

Execute the following script to test:

#!/usr/bin/env python
#coding=utf-8
 
from heat.common import mod
 
print mod.hello()
h = mod.Hello()
print h.test()
Copy after login

The execution results are as follows:

hello everyone
This is a test in Hello
Copy after login



If you need all the module files inside, just continue writing in the __init__.py file.

It should be noted that when a file is imported as a module, a .pyc file will be generated. If the module is changed, the .pyc file should be refreshed, otherwise the old information will still be read.

In order to prevent the file from being used as a module, we should add

to the file
if __name__ == &#39;__main__&#39;:
       pass               #这里是要执行的语句
Copy after login


这样就可以防止当文件是被用作模块使用时,不会被执行if下面的语句,如果是当做程序来执行时,则会执行下面的语句,一般用作测试。

本文出自 “ptallrights” 博客,请务必保留此出处http://ptallrights.blog.51cto.com/11151122/1793746

The above is the detailed content of Python learning object-oriented programming characteristics (2). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template