Python tour XI: object-oriented programming mode three properties: encapsulation, inheritance, polymorphism

First, the package

The contents of the package is the package somewhere, go after the call content is encapsulated in somewhere.

Therefore, when using the object-oriented characteristics of the package, to be noted:

  • Encapsulation of the content to somewhere
  • Call content is encapsulated from somewhere

The first step: The contents of the package to somewhere

It is a form of self parameter when executed obj1 = Foo ( 'jackson', 18), self equal obj1

When performing obj2 = Foo ( 'alex', 78), self equal obj2

So, in fact, is encapsulated into the content object obj1 and obj2, each object has a name and age properties, similar to the figure in the memory to store.

obj1 -> name = jackson & age = 18

obj2 -> name = alex & age = 78

Step two: Call package content from somewhere

When you call content is packaged, there are two cases:

  • Direct calls through the object
  • Indirect call through self

1. Call content is encapsulated by the object directly

The figure shows an object obj1 obj2 and stored in memory mode, according to the stored content format may be so packaged call: Object attribute name

class Foo:
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
obj1 = Foo('wupeiqi', 18)
print obj1.name    # 直接调用obj1对象的name属性
print obj1.age     # 直接调用obj1对象的age属性
 
obj2 = Foo('alex', 73)
print obj2.name    # 直接调用obj2对象的name属性
print obj2.age     # 直接调用obj2对象的age属性

2. Indirect call contents packaged by self

Performing the methods of the class required an indirect call contents packaged by self.

class Foo:
  
    def __init__(self, name, age):
        self.name = name
        self.age = age
  
    def detail(self):
        print self.name
        print self.age
  
obj1 = Foo('wupeiqi', 18)
obj1.detail()  # Python默认会将obj1传给self参数,即:obj1.detail(obj1),所以,此时方法内部的 self = obj1,即:self.name 是 wupeiqi ;self.age 是 18
  
obj2 = Foo('alex', 73)
obj2.detail()  # Python默认会将obj2传给self参数,即:obj1.detail(obj2),所以,此时方法内部的 self = obj2,即:self.name 是 alex ; self.age 是 78

Object-oriented package is actually used constructor encapsulation of the content object, and then packaged contents obtained indirectly or directly self through the object.

Exercise 1 : In the terminal outputs the following information

  • Xiao Ming, 10 years old, male, go to the mountains to cut firewood
  • Xiao Ming, 10 years old, male, drove to the northeast
  • Xiao Ming, 10 years old, male, love big health
  • Lao Li, 90 years old, male, go to the mountains to cut firewood
  • Lao Li, 90 years old, male, drove to the northeast
  • Lao Li, 90 years old, male, love big health

Code 1 (functional) as follows:

def kanchai(name, age, gender):
    print "%s,%s岁,%s,上山去砍柴" %(name, age, gender)
 
def qudongbei(name, age, gender):
    print "%s,%s岁,%s,开车去东北" %(name, age, gender)
 
def dabaojian(name, age, gender):
    print "%s,%s岁,%s,最爱大保健" %(name, age, gender)
 
kanchai('小明', 10, '男')
qudongbei('小明', 10, '男')
dabaojian('小明', 10, '男')
 
kanchai('老李', 90, '男')
qudongbei('老李', 90, '男')
dabaojian('老李', 90, '男')

Code 2 (object-oriented) as follows: 

class Foo:
 
    def __init__(self, name, age ,gender):
        self.name = name
        self.age = age
        self.gender = gender
 
    def kanchai(self):
        print "%s,%s岁,%s,上山去砍柴" %(self.name, self.age, self.gender)
 
    def qudongbei(self):
        print "%s,%s岁,%s,开车去东北" %(self.name, self.age, self.gender)
 
    def dabaojian(self):
        print "%s,%s岁,%s,最爱大保健" %(self.name, self.age, self.gender)
 
xiaoming = Foo('小明', 10, '男')
xiaoming.kanchai()
xiaoming.qudongbei()
xiaoming.dabaojian()
 
laoli = Foo('老李', 90, '男')
laoli.kanchai()
laoli.qudongbei()
laoli.dabaojian()

When the object-oriented manner, only creates an object; difficult seen from the above comparison, if a programming function, need to pass at each function performs the same parameter, if multiple parameters, then, requires a lot of copy paste , all the parameters required to the current package object, then when used again, go through the self indirect object value to the current.

English II : Writing Game of Life program

1, create three game characters, which are:

  • Aoi well, female, 18, 1000 initial fighting
  • Tony Wood, male, 20, 1800 initial fighting
  • A lot of waves, female, 19, 2500 initial fighting

2, game scenarios, respectively:

  • Grass fighting, fighting consumed 200
  • Self-cultivation, an increase of 100 combat
  • Multiplayer games, consume 500 combat
# -*- coding:utf-8 -*-
 
# #####################  定义实现功能的类  #####################
 
class Person:
 
    def __init__(self, na, gen, age, fig):
        self.name = na
        self.gender = gen
        self.age = age
        self.fight =fig
 
    def grassland(self):
        """注释:草丛战斗,消耗200战斗力"""
 
        self.fight = self.fight - 200
 
    def practice(self):
        """注释:自我修炼,增长100战斗力"""
 
        self.fight = self.fight + 200
 
    def incest(self):
        """注释:多人游戏,消耗500战斗力"""
 
        self.fight = self.fight - 500
 
    def detail(self):
        """注释:当前对象的详细情况"""
 
        temp = "姓名:%s ; 性别:%s ; 年龄:%s ; 战斗力:%s"  % (self.name, self.gender, self.age, self.fight)
        print temp
 
# #####################  开始游戏  #####################
 
cang = Person('苍井井', '女', 18, 1000)    # 创建苍井井角色
dong = Person('东尼木木', '男', 20, 1800)  # 创建东尼木木角色
bo = Person('波多多', '女', 19, 2500)      # 创建波多多角色
 
cang.incest() #苍井空参加一次多人游戏
dong.practice()#东尼木木自我修炼了一次
bo.grassland() #波多多参加一次草丛战斗
 
#输出当前所有人的详细情况
cang.detail()
dong.detail()
bo.detail()
 
cang.incest() #苍井空又参加一次多人游戏
dong.incest() #东尼木木也参加了一个多人游戏
bo.practice() #波多多自我修炼了一次
 
#输出当前所有人的详细情况
cang.detail()
dong.detail()
bo.detail()

Second, inheritance

Inheritance, object-oriented inheritance and real life inherit the same, namely: the child can inherit the contents of the Father.

E.g:

  Cats can: meow, eating, drinking, Caesar

  Dogs can: barking, eating, drinking, Caesar

If we want to create a class are cats and dogs, then you need to achieve all of their functions as cats and dogs, as follows:

class 猫:
 
    def 喵喵叫(self):
        print '喵喵叫'
 
    def 吃(self):
        # do something
 
    def 喝(self):
        # do something
 
    def 拉(self):
        # do something
 
    def 撒(self):
        # do something
 
class 狗:
 
    def 汪汪叫(self):
        print '喵喵叫'
 
    def 吃(self):
        # do something
 
    def 喝(self):
        # do something
 
    def 拉(self):
        # do something
 
    def 撒(self):
        # do something

 The code is easy to see, eating, drinking, Caesar cats and dogs have a function, and we have cats and dogs, respectively, in the preparation of the class twice. If you are using the idea of ​​inheritance, implemented as follows:

  Animals: eating, drinking, Caesar

     Cat: meow (cat inheritance animals)

     Dog: barking (dog inheritance animals)

class 动物:
 
    def 吃(self):
        # do something
 
    def 喝(self):
        # do something
 
    def 拉(self):
        # do something
 
    def 撒(self):
        # do something
 
# 在类后面括号中写入另外一个类名,表示当前类继承另外一个类
class 猫(动物):
 
    def 喵喵叫(self):
        print '喵喵叫'
 
# 在类后面括号中写入另外一个类名,表示当前类继承另外一个类
class 狗(动物):
 
    def 汪汪叫(self):
        print '喵喵叫'
class Animal:
 
    def eat(self):
        print "%s 吃 " %self.name
 
    def drink(self):
        print "%s 喝 " %self.name
 
    def shit(self):
        print "%s 拉 " %self.name
 
    def pee(self):
        print "%s 撒 " %self.name
 
class Cat(Animal):
 
    def __init__(self, name):
        self.name = name
        self.breed = '猫'
 
    def cry(self):
        print '喵喵叫'
 
class Dog(Animal):
 
    def __init__(self, name):
        self.name = name
        self.breed = '狗'
 
    def cry(self):
        print '汪汪叫'
 
# ######### 执行 #########
 
c1 = Cat('小白家的小黑猫')
c1.eat()
 
c2 = Cat('小黑的小白猫')
c2.drink()
 
d1 = Dog('胖子家的小瘦狗')
d1.eat()

Therefore, the object-oriented inheritance, in fact, is the more common method of extracting the class to the parent class, subclass inherits the parent class rather than just come true for each method.

Note: In addition to the title of the parent class and subclass, you've probably seen the derived class and the base class, with subclasses and their parent class is called just different.

After studying the inheritance of writing, we use the code to implement the functions Tun Town:

class Animal:
 
    def eat(self):
        print "%s 吃 " %self.name
 
    def drink(self):
        print "%s 喝 " %self.name
 
    def shit(self):
        print "%s 拉 " %self.name
 
    def pee(self):
        print "%s 撒 " %self.name
 
class Cat(Animal):
 
    def __init__(self, name):
        self.name = name
        self.breed = '猫'
 
    def cry(self):
        print '喵喵叫'
 
class Dog(Animal):
 
    def __init__(self, name):
        self.name = name
        self.breed = '狗'
 
    def cry(self):
        print '汪汪叫'
 
# ######### 执行 #########
 
c1 = Cat('小白家的小黑猫')
c1.eat()
 
c2 = Cat('小黑的小白猫')
c2.drink()
 
d1 = Dog('胖子家的小瘦狗')
d1.eat()

About class inheritance:

Class can inherit more than one class of 1. Python, Java and C # can only inherit a class

2. Python class that inherits if more than one class, then there are two methods to find their way, are: depth-first and breadth-first

  • When the class is a classic class, multiple inheritance case, looks for depth-first fashion
  • When the class is a new class, multiple inheritance cases, according to the breadth-first fashion looks

Classic and new method to distinguish between categories: if the  current class or object class inherits the parent class , then the class is new-style class, otherwise it is a classic class.

Classic: First go to A category Look, if A is not a class, then continue to B class find, if class B, it has, proceed to D class find, if the class D, it has, proceed to C class find, if still not found, then an error.

class D:
 
    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()
# 执行bar方法时
# 首先去A类中查找,如果A类中没有,则继续去B类中找,如果B类中么有,则继续去D类中找,如果D类中么有,则继续去C类中找,如果还是未找到,则报错
# 所以,查找顺序:A --> B --> D --> C
# 在上述查找bar方法的过程中,一旦找到,则寻找过程立即中断,便不会再继续找了
a.bar()

The new categories: First, go to A category Look, if A is not a class, then continue to B class find, if class B, it has, proceed to C class find, if class C Mody, continue to D class find, if still not found, then an error.

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()
# 执行bar方法时
# 首先去A类中查找,如果A类中没有,则继续去B类中找,如果B类中么有,则继续去C类中找,如果C类中么有,则继续去D类中找,如果还是未找到,则报错
# 所以,查找顺序:A --> B --> C --> D
# 在上述查找bar方法的过程中,一旦找到,则寻找过程立即中断,便不会再继续找了
a.bar()

Note: In the lookup process, once found, the process of finding immediately interrupted, will not continue to find them.

Polymorphism

Pyhon Java and C # does not support this type of polymorphism in a strongly typed language wording, but the native multi-state, its Python advocating "duck typing."

class F1:
    pass
 
class S1(F1):
 
    def show(self):
        print 'S1.show'
 
class S2(F1):
 
    def show(self):
        print 'S2.show'
 
# 由于在Java或C#中定义函数参数时,必须指定参数的类型
# 为了让Func函数既可以执行S1对象的show方法,又可以执行S2对象的show方法,所以,定义了一个S1和S2类的父类
# 而实际传入的参数是:S1对象和S2对象
 
def Func(F1 obj):
    """Func函数需要接收一个F1类型或者F1子类的类型"""
 
    print obj.show()
 
s1_obj = S1()
Func(s1_obj) # 在Func函数中传入S1类的对象 s1_obj,执行 S1 的show方法,结果:S1.show
 
s2_obj = S2()
Func(s2_obj) # 在Func函数中传入Ss类的对象 ss_obj,执行 Ss 的show方法,结果:S2.show
class F1:
    pass
 
class 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) 

To summarize this section:

  • Object-oriented programming is a way to achieve this is based on the programming mode  classes  and  objects  used
  • Class is a template, the template package a number of "function" for use
  • Objects, an example of a template created (namely: object), for instance are packed in calling a function in the class
  • Object-oriented three characteristics: encapsulation, polymorphism and inheritance

Q & Area

The question: what kind of code is object-oriented?

A: In short, if all the features of the program are used to implement classes and objects, then that is the object-oriented programming.

Second problem: how functional programming and object-oriented selection? It was used under what circumstances?

A: Notes: For C # and Java programmers do not have this problem because the only two languages ​​support object-oriented programming (functional programming is not supported). For Python and PHP programming language has to support two ways, and functional programming to complete the operation, the object-oriented can be achieved; and object-oriented to complete the operation, not functional programming (functional programming can not be achieved for encapsulation function objects).

Therefore, the general development of the Python, all object-oriented  or  object-oriented and functional mix

Object-oriented application scenarios:

  1. Multi-function need to use a common value, such as: the database to add, delete, change, operations need to connect to the database strings, the host name, user name and password
class SqlHelper:
 
    def __init__(self, host, user, pwd):
 
        self.host = host
        self.user = user
        self.pwd = pwd
 
    def 增(self):
        # 使用主机名、用户名、密码(self.host 、self.user 、self.pwd)打开数据库连接
        # do something
        # 关闭数据库连接
 
    def 删(self):
        # 使用主机名、用户名、密码(self.host 、self.user 、self.pwd)打开数据库连接
        # do something
        # 关闭数据库连接
 
    def 改(self):
        # 使用主机名、用户名、密码(self.host 、self.user 、self.pwd)打开数据库连接
        # do something
        # 关闭数据库连接
 
    def 查(self):
    # 使用主机名、用户名、密码(self.host 、self.user 、self.pwd)打开数据库连接
        # do something
        # 关闭数据库连接# do something

2. The need to create multiple things, the same number of each attribute thing, but the demand values
such as: Joe Smith, John Doe, Yang Five, they have a name, age, blood type, but it is not the same. That is: the same number of attributes, but the values are not identical

class Person:
 
    def __init__(self, name ,age ,blood_type):
 
        self.name = name
        self.age = age
        self.blood_type = blood_type
 
    def detail(self):
        temp = "i am %s, age %s , blood type %s " % (self.name, self.age, self.blood_type)
        print temp
 
zhangsan = Person('张三', 18, 'A')
lisi = Person('李四', 73, 'AB')
yangwu = Person('杨五', 84, 'A')

Question three: how classes and objects are stored in memory?

A: classes and methods in the class in a memory only, and according to each object class are created a need to save in memory, substantially as shown below:

As shown above, according to the object class is created when objects other than the value of the package name and age, but also to save a class object pointer , which points to the current value of the object class.

When the method of [a] is performed by obj1, as follows:

  1. Method according to class to find the current object pointer to the class object
  2. Obj1 object as a parameter passed to the method the first parameter self

 

Guess you like

Origin blog.csdn.net/xymalos/article/details/91963656