PythonDay7

每日一记

python中的面向对象:
编程语言的发展:机器语言 汇编语言 高级语言(面向过程的 c) 面向对象(c++ java python )
类:对具有相同属性和方法的抽象
对象:具有属性和方法的实物
面向对象的三大特性:继承,封装,多态
继承:
优点:减少代码量
缺点:耦合程度太高
高内聚 低耦合
构造函数:没有显示声明,系统会默认提供一个
子类使用父类属性时,必须手动调用父类构造函数
重写和覆盖:当父类方法不能满足子类需求
多继承:从左到右,一层一层寻找

定义一个人的属性和方法

class person():
    def __init__(self,name,age,sex,height):
        self.name = name
        self.age = age
        self.sex = sex
        self.height =height
        # return None
    def say(self):
        print(self.name,self.age,self.sex,self.height,"hello")
    #静态方法
    @staticmethod
    def run():
        print("跑步")

此处定义的属性是有返回值的,在最底层代码中已经写好了,我们在这就不需要再return了 ,如果想要return,可以return None

p = person("张三",18,"男",180)
p.say()
#__init__  构造函数
#self代表即将要出现的那个对象 ,临时指向新创建的对象
#方法(3): 类方法(2) 装饰器  静态方法      对象方法
person.run()
p.run()
print(p.name)

如果两个类的属性方法基本一致,例如:

class cat():
    def __init__(self,name,weight,age):
        self.name = name
        self.weight = weight
        self.age = age
    def eat(self):
        print("吃饭")
    def run(self):
        print("跑步")
    def sleep(self):
        print("睡觉")
class dog():
    def __init__(self,name,weight,age):
        self.name = name
        self.weight = weight
        self.age = age
    def eat(self):
        print("吃饭")
    def run(self):
        print("跑步")
    def sleep(self):
        print("睡觉")

猫和狗的属性方法都一致,这样定义他们的属性和方法就多此一举了,我们可以定义一个公共类来表示
定义一个annimal类:

class animal():
    def __init__(self, name, weight, age):
        self.name = name
        self.weight = weight
        self.age = age
    def eat(self):
        print("吃饭")
    def run(self):
        print("跑步")
    def sleep(self):
        print("睡觉")
class cat(animal):
    def __init__(self):
        super().__init__("小花",2,2)
    def eat(self):
        print("猫粮")
class dog(animal):
    def __init__(self):
        super().__init__("小黄",3,3)
    def eat(self):
        print("狗粮")
c = cat()
print(c.name)
c.eat()
d = dog()
print(d.name)
d.eat()

结果为

小花
猫粮
小黄
狗粮

多继承
父类与子类的关系

class gfather():
    def fun(self):
        print("参军")
class father0(gfather):
    def __init__(self):
        print("这是亲的")
    def fun(self):
        print("当大官")
class father1(gfather):
    def __init__(self):
        print("这是干爹1")
    def fun(self):
        print("多钱")
class father2(gfather):
    def __init__(self):
        print("这是干爹2")
    def fun(self):
        print("找媳妇")
class son(father0,father1,father2):
    pass
s = son()
s.fun()

输出结果

这是亲的
当大官

猜你喜欢

转载自blog.csdn.net/weixin_43895297/article/details/86581541