Object-oriented three characteristics of the python ----- encapsulation, inheritance, polymorphism

1, the package

Packaging is a major feature of object-oriented programming, the properties and methods of an abstract class encapsulates the
data is stored in the interior, the other parts of the program operates on the data only through authorized operation (Method member). Use outside class to create an object, and then let the object method call
by calling the instance method, we directly manipulate the internal data object, but without knowing the internal implementation details of the method. Details of the method of the object are encapsulated inside the class

------------------- Exercise------------------

Demand
1. Xiao Ming weighing 75.0 kg
2. Xiao Ming each run will lose 0.5 kg
3. Bob each eat one kilogram of body weight will increase

Demand
1. Xiao Ming and small beauty love running
2. Mel weighing 45.0 kg
2. Each runner will lose 0.5 kg
3. Each eat one kilogram of body weight will increase

class Person:
    def __init__(self,name,weight):
        self.name = name
        self.weight = weight
    def __str__(self):
        return '我的名字叫 %s 体重是 %.2f' %(self.name,self.weight)
# 在对象的方法内部,是可以直接访问对象的属性的
    def run(self):
        print('%s 去跑步~~~~' %(self.name))
        self.weight -= 0.5
    def eat(self):
        print('%s 去吃东西~~~' %(self.name))
        self.weight += 1
xiaoming = Person('小名',75.0)
xiaoming.run()
xiaoming.eat()
print(xiaoming)
xiaomei = Person('小美',45.0)
xiaomei.eat()
print(xiaomei)

------------------- Exercise------------------

Get grade achievement based on student achievement

class Student:
    def __init__(self,name,score):
        #初始化方法,当使用类创建实例的时候都会调该方法
        self.name = name
        self.score = score
    def get_grade(self):
        #对数据封装
        if self.score > 90:
            print('A')
        elif self.score >80:
            print('B')
        else:
            print('C')

toto = Student('toto',95)  # 创建对象
toto.get_grade()  # 直接使用对象调用方法,得到结果

#输出结果:
A

Property of an object to another object class can be created

------------------- Exercise------------------

Requirements:
1. apartment house has a total area of furniture and a list of names
new house is unfurnished
2. The furniture has a name and an area where
bed: 5
Tables: 4
Chairs: 6
3. Add furniture to house more than three in
4. Print the house, the required output: the total area of the remaining area apartment furniture name list

class Furniture:   # 限定义家具类
    def __init__(self,name,area):
        self.name = name
        self.area = area
    def __str__(self):
        return 'this is %s, %d square '

#使用类创建好对象之后,该对象可以作为参数用于其他函数调用。

class House:  #在定义房子类
    def __init__(self,type,squa):
        self.fu_list = []
        self.type = type
        self.leftsqua = self.allsqua = squa
    def __str__(self):
        return ' 户型是: %s\n 总面积是: %.2f\n 剩余面积: %.2f\n 家具列表:%s' \
               %(self.type,self.allsqua,self.leftsqua,self.fu_list)
    def add_furn(self,item):  # 在房子类的方法中使用的参数是家具类的一个实例
        if item.area<self.allsqua:
            self.fu_list.append(item.name)
            self.leftsqua -=item.area
        else:
            return
bed = Furniture('bed',5)
desk = Furniture('desk',4)
chair = Furniture('cabinet',6)   # 先实例化 家具

house1 = House('三室',120)  # 在实例化房子
house1.add_furn(bed)   # 再使用房子对象的方法,传入的参赛是家具实例
house1.add_furn(desk)
house1.add_furn(chair)
print(house1)

#输出结果:
 户型是: 三室
 总面积是: 120.00
 剩余面积: 105.00
 家具列表:['bed', 'desk', 'cabinet']

------------------- Exercise------------------

1. There are a soldier Ryan AK47
2. soldiers can fire (soldiers firing trigger is pulled)
3. gun capable of firing bullets (bullets fired out)
increasing the number of bullets - 4. gun bullets can be loaded

class Gun:   # 定义枪类
    def __init__(self,name):
        self.name = name
        self.count = 3   # 属性:枪名称以及子弹数量
    def add_bullet(self):  # 方法:添加子弹,将子弹数充值3
        self.count = 3
    def launch_bullet(self):   # 发射子弹
        if self.count <= 0:
            self.add_bullet()   #如果没有子弹,先进行添加子弹
        self.count -= 1   # 然后子弹减少一个
        print('%s 已经成功发射子弹 剩余子弹%d' %(self.name,self.count))

class Solair:   # 定义士兵类
    def __init__(self,name):
        self.name = name   # 设置属性 :name
    def shoot(self,gun):  # 定义方法:直接调用枪对象的方法
        gun.launch_bullet()


AK47 = Gun('AK47')   # 实例化一个枪对象
ryan = Solair('Ryan')   #实例化一个士兵对象
ryan.shoot(AK47)  # 士兵对象调用开火方法
ryan.shoot(AK47)
ryan.shoot(AK47)
ryan.shoot(AK47)

#结果:
AK47 已经成功发射子弹 剩余子弹2
AK47 已经成功发射子弹 剩余子弹1
AK47 已经成功发射子弹 剩余子弹0
AK47 已经成功发射子弹 剩余子弹2

2, inheritance

In OOP programming, when we define a class, they can inherit from an existing class, the new class is called a subclass (Subclass), and inherited class is called the base class, parent class or superclass (Base class, Super class)

The biggest advantage is a subclass get the full functionality of the parent class to achieve code reuse, you do not need to repeat the same code to write.

class Animal():  #定义动物类
    def run(self):
        print('running~~')
    def call(self):
        print('hahahah')   # 动物类中存在两个方法

class Cat(Animal):   # 定义猫类,继承动物类
    pass  
tom = Cat()  # 常见一个猫类实例
tom.run()  # 该实例可以直接调用动物类的方法

#输出结果:
running~~

Some methods can add their own specific function in a subclass

class Animal():
    def run(self):
        print('running~~')
    def call(self):
        print('hahahah')
class Cat(Animal):
    def eat(self):
        print('爱吃鱼')
tom = Cat()
tom.run()  # 调用父类的方法
tom.eat()  # 使用自己类的方法

#输出结果:
running~~
爱吃鱼

When the parent class method can not achieve the full requirements of virtual subclass can be rewritten method, we say, subclass covers methods of the parent class, when the code is running, always call the method subclass .

class Animal():
    def run(self):
        print('running~~')   #父类中存在run方法
    def call(self):
        print('hahahah')
class Cat(Animal):
    def run(self):
        print('跑得快')    # 子类中也存在run方法
    def eat(self):
        print('爱吃鱼')
tom = Cat()
tom.run()   # 当实例调用run方法的时候,总是调用的子类中的程序

#运行结果:
跑得快

It can be extended to the method of the parent class. Preserve the contents of the parent class method, adding new content on its basis. Only the same manner as defined in the sub-subclasses and superclasses in need thereof, and writes in the method super (). Call () (parent class method (self) python2.x achieved by the two), then add the required extended the content can be.

class Animal():
    def run(self):
        print('running~~')
    def call(self):
        print('hahahah')
class Cat(Animal):
    def run(self):
        super().run()    # 继承父类给方法的内容,同时添加扩展的内容
        print('跑得快')
    def eat(self):
        print('爱吃鱼')
tom = Cat()
tom.run()

#输出结果:
running~~
跑得快

When the parent class using the initialization method in a subclass also want to use the initialization method when the need to use the super sub class initialization method (). The init (), expressed inherited an extension of the parent class initialization method, should not , there will be a conflict error.

class Animal():
    def __init__(self,name):
        self.name = name
    def run(self):
        print('running~~')
    def call(self):
        print('hahahah')
class Cat(Animal):
    def __init__(self,color,name):
        super().__init__(name)   #在子类中必须使用该语句,表示继承父类中的属性。
        self.color = color
    def run(self):
        super().run()
        print('跑得快')
    def eat(self):
        print('爱吃鱼')
tom = Cat('tom','red')
print(tom.name)
print(tom.color)

#输出结果:
red
tom

When a plurality of sub-subclass inherits the parent class, and there are a plurality of the same parent class method, the instance of this subclass when calling this method takes time, that there will be inherited parent class EDITORIAL which method to use a parent class. Recommended method definition, try not to use the same name

class A:   #定义A 类
    def lala(self):
        print('lala')
    def toto(self):
        print('toto')  # 其中由来两个方法
class B:  # 定义B类
    def lala(self):
        print('LALA')
    def toto(self):
        print('TOTO')   # 其中由两个方法,并且方法名称和A中方法名称一致
class C(A,B):   #定义类C 继承A,B 两个类
    pass
class D(B,A):   # 定义类D 继承B,A 两个类
    pass

c = C()
d = D()

c.lala()  
d.lala()

c.toto()
d.toto()    # 当继承父类的顺序不同的时候,导致调用的方法是不同的内容,默认调用位置靠前的父类方法

#输出结果:
lala
LALA
toto
TOTO

3, polymorphism

Different results are encapsulation and inheritance premise, there is a function that requires a parameter, not a function of the parameter to be modified when the object is different when the output,

It refers to the same manner as a class instance can have different forms in different situations. Of polymorphism so that objects having different internal structures can share the same external interface. This means that, although different specific actions for different objects, but through a common class, they (those operations) can be invoked in the same way.

Different subclass object calls the same method, generating different results of execution

First data type and then a few notes. When we define a class, we actually define a data type. We define data types and comes with Python data types, such as str, list, dict no different class Animal (object):

    def run(self):
        print('Animal is running...')

class Dog(Animal):
    pass

class Cat(Animal):
    pass

a = list()
b = Animal()
c = Dog()
d = Cat()

print(isinstance(a,list))
print(isinstance(b,Animal))
print(isinstance(c,Dog))
print(isinstance(d,Cat))

#输出结果:
True
True
True
True

While the child out of the object class is instantiated, not only it is a subclass of the type, also the type of the parent class. In the hierarchy, if the data type is an instance of a subclass of the type of data that it can also be seen as a parent. Animal Dog example, a parent class, using Dog instantiate an instance, that instance is both Dog type, also Animal type.

class Animal(object):
    def run(self):
        print('Animal is running...')

class Dog(Animal):
    pass

b = Animal()
c = Dog()

print(isinstance(b,Animal))
print(isinstance(c,Dog))
print(isinstance(c,Animal))

#输出结果:
True
True
True

First, there are three categories: Animal, Dog, Cat; Dog, Cat Animal class inherits from, and there run method.

 class Animal(object):
    def run(self):
        print('Animal is running...')
class Dog(Animal):
    def run(self):
        print('Dog is running')
class Cat(Animal):
    def run(self):
        print('Cat is running')

Understand the benefits of polymorphism, we still need to write a function that accepts a variable of type Animal:

   def run_twice(animal):
        animal.run()
        animal.run()
当我们传入Animal类的实例时,run_twice()就打印出:
def run_twice(animal):
    animal.run()
    animal.run()

run_twice(Animal())

#输出结果:
Animal is running...
Animal is running...

Since examples and examples of Cat Dog Animal class can be a data type, it may also function as the argument, as class instances and Cat Dog incoming class, output of the function:

def run_twice(animal):
    animal.run()
    animal.run()

run_twice(Dog())
run_twice(Cat())

#输出结果:
Dog is running
Dog is running

Cat is running
Cat is running

Animal now to a parent class as a subclass definition, and examples thereof as an argument, a function can run_twice normal operation.

class Tortoise(Animal):
    def run(self):
        print('Tortoise is running slowly~~~')
run_twice(Tortoise())

#输出结果:
Tortoise is running slowly~~~
Tortoise is running slowly~~~

Key:

A new subclass of Animal, do not have run_twice () to make any changes, in fact, any dependency or as a function of Animal method parameters are running without modification,

Animal function requires a parameter of type, when we need to pass Dog, Cat, Tortoise ......, we only need to receive its Animal type on it, because Dog, Cat, Tortoise ...... all Animal type, and then, in accordance with the Animal type can operate. Function to normal operation.

Since Animal types run () method, therefore, the incoming any type as long as the Animal class or subclass, will automatically call the actual type of run () method, of course, the contents of each RUN method and the actual type of operation data are not the same, the results will operate the same, this is polymorphism.

For a variable, we just need to know that it is Animal type, without having to know exactly which sub-type, you can call the run () method safely, and run specific call () method is the role of the Animal, Dog, Cat or Tortoise on the object, the exact type of the object is determined by the runtime,

The caller just calls, regardless of the details, and when we add one kind of Animal subclass of, just make sure run () method to write correctly, do not control how the original code is called. This is the famous "opening and closing" principle:

Open for extension: New Animal allow subclasses
closed for modification: Animal no modification dependent type run_twice () function and the like.

Guess you like

Origin blog.csdn.net/qq_36016375/article/details/92798782