1.声明一个电脑类:
属性:品牌、颜色、内存大小
方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关方法去获取、修改、添加和删除它的属性
class Cumpter:
def __init__(self,band = "au",color ="blace",size = 520):
self.band = band
self.color = color
self.size = size
def play_game(self):
return print("可以打游戏,写代码,看视频")
if __name__ == "__main__":
cum1 = Cumpter("lione","red",500)
print(cum1.size)
print(cum1.__getattribute__("size"))
print(getattr(cum1,"size"))
cum1.band ="lianxiang"
print(cum1.band)
print(cum1.__setattr__("band","huashuo"),)
print(setattr(cum1,"band","jinji"))
del cum1.size
print(cum1.size)
2.声明一个人的类和狗的类:
狗的属性:名字、颜色、年龄 狗的方法:叫唤
人的属性:名字、年龄、狗 人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Dog:
def __init__(self,name,color,age):
self.name = name
self.color = color
self.age = age
def dog_active(self):
return print("叫唤")
class Man:
def __init__(self,name,color,dog):
self.name = name
self.color = color
self.dog = dog
def man_action(self):
return print("遛狗")
dog1 = Dog("dahaung","red",3)
man1 = Man("xiaoming","yellow",dog1)
print("%s有只%s" % man1.name,dog1.name)
print("xiaoming",man1.man_action(),dog1.dog_active())
3.声明一个矩形类:
属性:长、宽 方法:计算周长和面积 ””
a.创建不同的矩形,并且打印其周长和面积
class React:
def __init__(self,x,y):
self.x = x
self.y = y
def perimeter(self):
len = self.x*2+self.y*2
print(len)
react1 = React(4,5)
react1.perimeter()
5.写一个类,封装所有和数学运算相关的功能(包含常用功能和常用值,例如:pi,e等)
class Math :
def __init__(self, list=[]):
self.list = list
def sum_fa(self):
x = 0
for index in math1.list:
x += index
print(x)
math1 = Math([1,2,3])
print(math1.list)
math1.sum_fa()
6.1.写一个班级类,属性:班级名、学生;功能:添加学生、删除学生、根据姓名查看学生信息,展示班级的所有学生信息
class Student:
def __init__(self,name="",age=0):
self.name = name
self.age = age
def __str__(self):
return print("name:%s age:%d" % (self.name,self.age))
class Class:
def __init__(self,name="",students = []):
self.name = name
self.students = students
def add_student(self):
name = input("name:")
age = input("age:")
stu = Student(name,int(age))
self.students.append(stu)
cls1 = Class("py1805",[])
cls1.add_student()
print(cls1.students[0])