1.声明 个电脑类: 属性:品牌、颜色 、内存方法:打游戏、写代码、看视频;
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关 法去获取、修改、添加和删除它的属性
class Computer: def __init__(self, brand, color, ram): self.brand = brand self.color = color self.ram = ram def paly_computegame(self): print('打游戏') def write_code (self): print('打游戏') def watch_video(self): print('看视频') computer1 = Computer(brand='dell', color='black',ram = 2048)
#查看 print(computer1.ram) getattr(computer1, 'ram', 0) # 增加 computer1.cpu = 'i5' setattr(computer1, 'graphics card', 'gta950') # 删除 del computer1.brand delattr(computer1, 'brand') computer1.brand = 'lever' setattr(computer1, 'color' 'yellow')
2.声明⼀个⼈的类和狗的类:
狗的属性:名字、颜⾊、年龄 狗的⽅法:叫唤
⼈的属性:名字、年龄、狗 ⼈的⽅法:遛狗
a.创建⼈的对象⼩明,让他拥有⼀条狗⼤⻩,然后让⼩明去遛⼤⻩
class Dog: def __init__(self,name,color,age): self.name = name self.color = color self.age= age def dog_call(self): return '汪~' dog1 = Dog(name='大黄', color='yellow', age= 1) class Person: def __init__(self, name,age,dog): self.name = name self.age = age self.age = dog def walk_dog(self): return dog1.dog_call() p1 = Person(name='小明', age=18 , dog=dog1) print(p1.walk_dog())
3.声明⼀个矩形类:
属性:⻓、宽 ⽅法:计算周⻓和⾯积
a.创建不同的矩形,并且打印其周⻓和⾯积
class Rectangle : def __init__(self,long,wide): self.long = long self.wide = wide def perimeter_area (self): return (self.long+self.wide *2),self.long*self.wide jx1 = Rectangle(2,3) print(jx1.perimeter_area())