##### python three characteristics of object-oriented #####

Object-oriented programming has many advantages:

1, development time is short, high efficiency, high reliability, developed by the program stronger. Because of the reusability of object-oriented programming may be employed a large number of mature libraries in the application, thereby shortening the development time.

2, the application easier to maintain, update and upgrade. Effects of inheritance and encapsulation allows the application of modified bring more localized.

1. Object-oriented three characteristics: a package (Encapsulation), inherited (Inheritance), polymorphism (Polymorphism)
Here Insert Picture Description
Inheritance: A unifying model inheritance hierarchy is the class, and allows the reuse and encouraged, it provides a clearly stated common methods. A new class of objects can be derived from existing classes, this process is called class inheritance. The new class inherits the properties of the original class, the new class known as the original class of the derived class (subclass), while the original class is called the base class for the new class (parent class). A derived class can inherit methods and instance variables from its base class, and the class may modify or add new method makes it more suitable for particular needs. It also reflects the general relationship between nature and special. We inherited a good solution to the problem of software reusability. For example, all Windows applications have a window, they can be regarded as are derived from a window class. However, application programs for word processing, some applications for drawing, which is derived due to the different sub-categories, each subclass adds different characteristics.

  • The biggest advantage is a subclass of parent class to get full functionality, code reuse
class Animal:
   def eat(self):
      print('%s爱吃' %(self.name))
   def drink(self):
      print('%s要喝水' %(self.name))
class Cat(Animal):
   def __init__(self,name):
      self.name = name
   def sleep(self):
      print('%s爱睡觉' %(self.name))
class Dog(Animal):
   def __init__(self,name):
      self.name = name
   def dance(self):
      print('%s爱跳' %(self.name))
cat1 = Cat('tom')
cat1.sleep()
cat1.drink()
cat1.eat()

dog1 = Dog('Jeck')
dog1.drink()
dog1.dance()
运行:
tom要喝水
tom爱吃
Jeck要喝水
Jeck爱跳

Process finished with exit code 0

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.

在这里插入代码片

Animal class ():
DEF RUN (Self):
Print ( 'running ~ ~')
DEF Call (Self):
Print ( 'hahahah')
class Cat (Animal):
DEF RUN (Self):
Super () RUN (). # inherit the parent content to a method of simultaneously adding the content of the extended
print ( 'run fast')
DEF EAT (Self):
print ( 'love fish')
Tom Cat = ()
tom.run ()

# Output:
running ~ ~
run faster
when using the parent class initialization method, in subclasses also want to use the initialization process, the need to use the super sub-class initialization process (). The init (), expressed extended inherited initialization method of the parent class, 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

Encapsulation:

Packaging is one of the features of object-oriented concepts and the main properties of the object classes. Encapsulation is surrounded by the process and data, access to the data only through a defined interface. Object-oriented computing began in the basic notion that the real world can be represented as a series of fully autonomous, encapsulated objects that access other objects through a protected interface. Once the characteristics of an object is defined, it is necessary to determine the visibility of these characteristics, ie characteristics which are visible to the outside world, which are used to represent internal state. The object is defined at this stage interface. Generally, it should prohibit direct access to the actual representation of an object, but should be accessible through the user interface object, which is called information hiding. In fact, information hiding is user awareness of the encapsulation of the package was to support information hiding. Encapsulating module having better ensure independence, such modified program maintenance easier. Modify the application was limited to the class, which can be modified to reduce the impact to a minimum application.

class Person:  ##定义一个类
    def __init__(self,name,age,gender):  #类属性有姓名、年龄和性别
        self.name = name
        self.age = age
        self.gender = gender
    def eat(self):
        print("%s今年%s岁%s,喜欢布娃娃" %(self.name,self.age,self.gender))  #构造类方法将其封装到对象中,通过对象调取
    def study(self):
        print("%s今年%s岁%s,爱学习" % (self.name, self.age, self.gender))
    def paint(self):
        print("%s今年%s岁%s,爱画画" % (self.name, self.age, self.gender))
name = Person("lily",10,"女")  #创建的对象
name.eat()
name.study()
name.paint()

Example 1 Description: meet the following requirements
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 'this is %s ,my weight is %.2f ' %(self.name,self.weight)
    def eat(self):
        print('%s 吃饭' %self.name)
        self.weight += 1
    def run(self):
        print('%s 跑步' %self.name)
        self.weight -= 0.5
#将属性和方法都封装在一个类中


xiaoming = Person('xiaoming',70)  # 使用列创建对象
xiaoming.eat()  # 使用对象调用方法
xiaoming.run()
print(xiaoming)
xiaohua = Person('xiaohua',45)
xiaohua.eat()
xiaohua.run()
print(xiaohua)

#输出结果:
xiaoming 吃饭
xiaoming 跑步
this is xiaoming ,my weight is 70.50 
xiaohua 吃饭
xiaohua 跑步
this is xiaohua ,my weight is 45.50 

2 rating results obtained in accordance with 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

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']

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

Polymorphism:

Polymorphism is to allow objects of different classes respond to the same message. Such as adding the same, time the two together and the two integers together certainly completely different. As another example, the same select Edit - paste operation, have different effects in a drawing program and a word processing program. Polymorphisms include parametric polymorphism containing polymorphism. Polymorphism flexible language, abstract, behavior sharing, code-sharing advantages of a good solution to the problem of the application function of the same name.
  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 is 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()

When we passed the Animal class's instance, run_twice () to print out:

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~~~

Guess you like

Origin blog.csdn.net/weixin_44821839/article/details/92375444