1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self,brand:str,color:str,memory=0):
self.brand=brand
self.color=color
self.memory=memory
def play_games(self):
print("The feture of playing game")
def coding(self):
print("The feture of coding")
def video(self):
print("The feture of watching video")
com1=Computer("apple","white",memory=4096)
print(com1.__dict__)
print(com1.brand)#查
com1.memory=2048#改
print(com1.memory)
com1.price=124455#增
print(com1.price)
del com1.color#删除
print(com1.__dict__)
com2=Computer("Thinkpad","black",memory=1565)
print(com2.__dict__)
print(getattr(com2,"brand","None"))#查
setattr(com2,"memory",4096)#改
print(getattr(com2,"memory","None"))
setattr(com2,"price",17554)#增
print(getattr(com2,"price","None"))
delattr(com2,"color")#删除
print(com2.__dict__)
{'brand': 'apple', 'color': 'white', 'memory': 4096}
apple
2048
124455
{'brand': 'apple', 'memory': 2048, 'price': 124455}
{'brand': 'Thinkpad', 'color': 'black', 'memory': 1565}
Thinkpad
4096
17554
{'brand': 'Thinkpad', 'memory': 4096, 'price': 17554}
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Dog:
def __init__(self,name:str,color:str,age=0):
self.name=name
self.color=color
self.age=age
def bellowing(self):
print("wang...wang...wang..")
class Person:
def __init__(self,name:str,dog:str,age=0,):
self.name=name
self.age=age
self.dog=dog
def take_the_dog(self):
print("%s遛%s"%(self.name,self.dog))
dog1=Dog("大黄","yellow",age=6)
print(dog1.__dict__)
dog1.bellowing()
boy=Person("小明","大黄",age=18)
print(boy.__dict__)
boy.take_the_dog()
{'name': '大黄', 'color': 'yellow', 'age': 6}
wang...wang...wang..
{'name': '小明', 'age': 18, 'dog': '大黄'}
小明遛大黄
3.声明⼀一个圆类,自己确定有哪些属性和方法
import math
class Circle:
def __init__(self,radius):
self.radius=radius
def perimeter(self):
return 2*(self.radius)*math.pi
def area(self):
return(self.radius)**2 *math.pi
cir1=Circle(3)
print("area:%.2f"%cir1.area())
print("perimeter:%.2f"%cir1.perimeter())
area:28.27
perimeter:18.85