Self-taught python-three characteristics of object-oriented: encapsulation, inheritance, polymorphism

One, packaging

1. As the name implies, the content is encapsulated somewhere, and then the content encapsulated somewhere will be called later.
2. The privatization of attributes cannot be directly accessed externally, but can be accessed indirectly (through methods).
Therefore, when using object-oriented encapsulation features, you need to:
·
encapsulate the content somewhere · call the encapsulated content from somewhere

Encapsulation

#隐藏属性,在外部不可以对属性直接访问,可以间接访问,提供属性值的安全性。
#1.顾名思义就是将内容封装到某个地方,以后再去调用被封装在某处的内容。
#第一步:将内容封装到某处
class People():
	  def __init__(self,name,age):
	        self.name = name
	        self.age = age
	    def show(self):
	        print(self.name,self.age)
	        
p1 = People('张三',22)
p1.show()
p2 = People('张三2',12)
p2.show()	 
#把数据张三,22,张三2,12分别封装到p1,p2 中	 
#从某处调用被封装的内容
#调用被封装的内容时,有两种情况:
#通过对象直接调用
print(p1.name)
#通过self间接调用
def show(self):
    print(self.name,self.age) 
#面向对象的封装来说,其实就是使用构造方法将内容封装到 对象中,然后通过对象直接或者self间接获取被封装的内容

#2.对属性私有化 ,在外部不能直接访问,可以间接访问(通过方法)
__xx(左边只有两个下划线):类的私有变量,只能是允许这个类本身进行访问了,连子类也不可以
class people():
    def __init__(self):
        self.age = 2  # 实例属性(对象)
        self.__name=""

    def showinfo(self):
        print("名字:",self.__name)
        print("年龄:",self.age)

    #设置值
    def set_name(self,name):
        self.__name=name

    #获取值
    def get_name(self):
        return self.__name
        
#创建对象
p=people()
p.set_name("aa")
print(p.get_name())  

Second, inheritance

1. Inheritance, object-oriented inheritance is the same as inheritance in real life, that is, the child can inherit the content of the parent.
2. Function: It is one of the important means to realize code reuse in object-oriented language, which is convenient for expansion. Java only supports single-root inheritance, that is, a class can only have one direct parent class, and python can have multiple inheritance.

For example:
  cats can: meow, eat, drink, pull, and scatter
Dogs can: barks, eat, drink, pull, scatter

If we want to create a class for cats and dogs, then we need to implement all their functions for cats and dogs, as shown below:

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 above code is not difficult to see that eating, drinking, pulling, and spreading are functions that cats and dogs have, but we have written them twice in the cat and dog classes respectively. If you use the idea of ​​inheritance, the implementation is as follows:
   Animals: eat, drink, pull, and spread (parent class, base class)
   cat: meow (cat inherits the function of animals)
   dog: barking (dog inherits the function of animals) The
code is as follows :

#继承
#作用重用代码,扩展代码
#语法
#class a(父类):
#只要不是私有的属性和方法,都可以继承
class animal():

    def eat(self):
        print("动物在吃。。。")

    def sleep(self):
        print("动物在睡觉。。。")

class dog(animal):

    def dog_say(self):
        print("狗在叫。。。汪汪。。。")

class cat(animal):

    def cat_say(self):
        print("猫在叫。。。喵喵。。。")


d = dog()
d.sleep()#父类继承的方法(重用)
d.dog_say()#扩展
c = cat()
c.sleep()#父类继承的方法(重用)
c.cat_say()#扩展

Therefore, for object-oriented inheritance, it is actually extracting the methods shared by multiple classes into the parent class, and the subclass only needs to inherit the parent class without having to implement each method one by one.

Multiple inheritance:

Class A ():
      Def a():
          Print(“a”)
 
Calss B():
   
   Def b():
       Print(“b”)
 
Class C (A,B):
  
   Def c():
      Print(“c”)
      
C =C()
C.a()
C.b()
C.c()
 
显示结果 a b  c

Rewrite:

子类不想原封不动地继承父类的方法,而是想作一定的修改,这就需要采用方法的重写。方法重写又称方法覆盖。
	#方法重写
	#子类不想原封不动地继承父类的方法,而是想作一定的修改,这就需要采用方法的重写。方法重写又称方法覆盖。
	#参数和方法名都不能改,只改方法体
	
class animal():

    def eat(self):
        print("动物在吃。。。")	
        
class dog(animal):

    def eat(self):
        print("狗吃骨头。。。")
        
class cat(animal):

    def eat(self):
        print("猫吃鱼。。。")
d = dog()
d.eat()

super:

#super 调用父类方法
#调用父类中的方法或者属性
#super 调用父类方法
#调用父类中的方法或者属性

class animal():

    def __init__(self,name,color=""):
        self.name=name
        self.color=color

    def sleep(self):
        print(self.name,"动物在睡觉。。。")

    def eat(self):
        print("动物在吃。。。")

class dog(animal):

    def __init__(self,number,name,color):
        # 调用父类的构造方法
        super(dog, self).__init__(name)
        self.number=number#扩展的属性

    def eat(self):
        print(self.name,self.color,self.number,"狗吃骨头。。。")

class cat(animal):

    def eat(self):
        print("猫吃鱼。。。")

d = dog("小白","白色",2)
d.eat()

dir() function:

 #获得一个对象的所有属性和方法,可以使用 dir() 函数,它返回一个包含字符串的 list。
 #私有变量和方法  在其他地方不可以访问,不是绝对的,可以通过 dir()查看私有属性,直接访问。

class people():

    def __init__(self,name):
        self.__name=name
        self.age=0

p=people("a")
#print(dir(p))
print(p._people__name)
p.address="北京市"
print(p.address)

object root class
The base class of all classes in Python is Object

#object 根类
#__new__ 执行在__init__之前
#如果__new__ 没有返回新的对象,则不会执行__init__返回
#在 __new__方法中返回的return  object.__new__(cls)对象,实际就是__init__中self对象
#__str__ 把当前对象转换成str,在打印对象时,默认调用
#__xx__(两边两个下划线):是特列方法像__init__之类的,是python的内嵌的方法在特定的时候会被自动调用

class Monkey(object):

    def speak(self):
        print("咿咿呀呀......")

class people(Monkey):

    #Create and return a new object创建并返回新的对象

    def __new__(cls, *args, **kwargs):
        print("__new__")
        return  object.__new__(cls)

    #构造方法
    def __init__(self, name):
        print("__init__")
        self.name = name

    def speak(self):
        print("小样的,不错嘛!会说话了!")

    def think(self):
        print("别说话!认真思考!")

    def __str__(self):
        return "重写的str方法"+self.name

    def __del__(self):
        print("删除对象")

p = people("a")

#判断对象是否是那种数据类型
#print(isinstance(p,object))

#type()  查看

#打印对象时,默认调用__str__()
#print(p)
del p

Three, polymorphism

A type has multiple forms.
Function: frequently modify the code, you can use polymorphism to solve the expansion, maintenance

class cat():
    def __init__(self,name):
        self.name=name

    def say(self):
        print("喵喵。。。")


class dog():
    def __init__(self,name):
        self.name=name

    def say(self):
        print("汪汪。。。")

class people():

    def __init__(self,name):
        self.name=name

    #养宠物
    def set_pet(self,pet):
        self.pet=pet

    #让宠物叫
    def show_pet(self):
        print(self.name,"让宠物叫")
        self.pet.say()

g = dog("小黄")
c = cat("小花")
p = people("jack")
#养宠物
p.set_pet(g)
#让宠物叫
p.show_pet()

Guess you like

Origin blog.csdn.net/weixin_47580822/article/details/113726983