class Mobile: # 类属性 can_call = True def __init__(self, brand, color): self.brand = brand self.color = color def sell(self, price, discount=1): print(f'手机被卖了{price*discount}元') return price def call(self): print('正在打电话') self.take_photo() def take_photo(self): print('拍照') # 类方法的定义 声明类方法 @classmethod def abc(cls): print(f'这个类{cls}正在使用abc') @staticmethod def baozhaung(): """ 没有固定参数,与类和对象没有直接关联 无法使用self.属性和其他实例方法 无法使用cls.属性 和其他类方法 """ print('这是一个静态方法') class SmartPhone(Mobile): pass # 父类的所有的属性和方法,子类都可以用 xiaomi = SmartPhone('xiaomi', '粉色') xiaomi.call()
""" 方法重写:重写父类的方法 当自己有对应的方法或属性,优先使用自己的,如果自己没有则往上一层一层找 多重继承:子类(父类1, 父类2) super().方法 调用父类的方法 """ class Mobile: can_call = True def call(self): print('正在打电话') class SmartPhone(Mobile): def call(self): super().call() # 使用父类的方法,即会先执行父类里的call方法 print('智能手机正在打电话') class MusicPlayer: def play_music(self): print('正在放音乐') class Iphone(SmartPhone, MusicPlayer): """ 多重继承 """ def call(self): print('苹果手机正在打电话') xiaomi = SmartPhone() xiaomi.call() iphone = Iphone() iphone.call() iphone.play_music()
class Mobile: color = '黑色' # 获取属性 print(Mobile.color) # 获取属性不常用的方法 print(getattr(Mobile, 'color'))
# 如果获取的属性不存在,默认返回None,也可以设置默认值
print(getattr(Mobile, 'aaa', '默认值'))
# 以上两种方法的区别:getattr,属性可作为字符传进来 # p_name = input('输入属性:') # print(getattr(Mobile, p_name)) # 设置属性1 Mobile.logo = 'apple' # 设置属性2 setattr(Mobile, 'hh', '123') print(Mobile.logo) print(Mobile.hh) Mobile.color = '黄色' # 修改属性 print(Mobile.color)