python继承语法_python基础语法__继承23

Animal包含Dog类,Animal是父类,Dog是Animal的子类

1 继承:一个类可以继承另一个类的所有属性和方法。

2 方法重写:如果父类和子类有相同的方法和属性,先调用子类的

class Animal:

def run(self):

print("animal running~")

class Dog(Animal):

def run(self):

print("dog running~")

your_dog = Dog()

your_dog.run()

3 多重继承:有多个类的继承关系

class Bad:

def like(self):

print("拆家~")

class Erha(Dog, Bad):

pass

his_dog = Erha()

his_dog.run()

his_dog.like()

4 获取继承的优先调用顺序

print(Erha.__mro__)

5 super():子类方法想要调用父类的任何方法,这种继承叫做超继承

class Animal:

def __init__(self, ke, color):

self.ke = ke

self.color = color

def run(self):

print("animal run")

def eat(self):

print("animal eat")

class Dog(Animal):

def __init__(self, color, kind):

# 调用父类初始化函数,然后再定义自己的特征

# self.color = color

super().__init__("dog", color)

self.kind = kind

def run(self):

super().run()

print("dog run")

super().eat()

self.eat()

his_dog = Dog("白色","阿拉斯加")

print(his_dog.ke)

print(his_dog.color)

his_dog.run()

6 getattr() 获取某个属性,如果属性不存在会返回默认值,没有默认值则报错

class Dog:

def __init__(self, color):

self.color = color

self.ke = "dog"

dog = Dog("red")

用户自己控制获取哪个属性

data = getattr(dog,"color")

print(data)

user_input = input("请输入想要获取的属性: ")

data = getattr(dog, user_input, "NO")

print(data)

7 serattr() 设置某个属性

setattr(dog, "gender", "女")

print(dog.gender)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值