1.声明个电脑类: 属性:品牌、颜 、内存 法:打游戏、写代码、看视频
class Computer:
def __init__(self, brand, color, memory):
self.brand = brand
self.color = color
self.memory = memory
def playgames(self):
print('打游戏')
return
def write(self):
print('写代码')
return
def look(self):
print('看视频')
return
if __name__ == '__main__':
a1 = Computer('华硕', '黄色', '1t')
print(a1.playgames())
print(a1.write())
print(a1.look())
a.创建电脑类的对象,然后通过对象点的 式获取、修改、添加和删除它的属性 b.通过attr相关 法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self, brand, color, memory):
self.brand = '华硕'
self.color = '黑色'
self.memory = '1t'
if __name__ == '__main__':
p1 = Computer('华硕', '黄色', '1t')
print(p1.brand, p1.memory, p1.color)
p1.brand = '惠普'
p1.color = '白色'
p1.memory = '2t'
print(p1.brand, p1.memory, p1.color)
p1.master = '吕耐芯'
print(p1.brand, p1.memory, p1.color, p1.master)
del p1.master
print(p1.brand, p1.memory, p1.color)
print(getattr(p1, 'brand'))
print(getattr(p1, 'color', '灰色'))
setattr(p1, 'weight', '120g')
print(p1.weight)
print(delattr(p1, 'color'))
2.声明 个 的类和狗的类:狗的属性:名字、颜 、 龄 狗的 法:叫唤 的属性:名字、 龄、狗 的 法:遛狗 a.创建 的对象 明,让他拥有 条狗 ,然后让 明去遛
class People:
def __init__(self, name, age):
self.name = name
self.age = age
def methods(self):
print('遛狗')
return
class Dog:
def __init__(self, name, color, age):
self.name2 = name
self.color2 = color
self.age2 = age
def methonds2(self):
print('汪汪汪')
return
if __name__ == '__main__':
m = People('小明','10')
m.methods()
print(m.methods())
n = Dog('1岁', '黄色', '大黄狗')
n.methonds2()
print(n.methonds2())
3.声明 个矩形类:属性: 、宽 法:计算周 和 积 a.创建 同的矩形,并且打印其周 和 积
class Ju:
def __init__(self, long, width):
self.long = long
self.width = width
def actions(self):
return (self.width+self.long)*2 , self.width * self.long
if __name__ == '__main__':
s = Ju(3,4)
print(s.actions())
4.创建 个学 类:属性:姓名, 龄,学号 法:答到,展示学 信息 创建 个班级类: 属性:学 ,班级名 法:添加学 ,删除学 ,点名
class literature:
def __init__(self, name, age, number):
self.name = name
self.age = age
self.number = number
def displays(self):
return s
class Class1:
def __init__(self, class_name):
self.stu = []
self.class_name =class_name
def add(self,student):
self.stu.append(student)
def dels(self,student):
if self.stu:
self.stu.remove(student)
def dian(self,student):
for student in self.stu:
print(student.name)
if __name__ == '__main__':
s = literature('吕耐芯', '22', '20152102514')
print(s.name, s.age, s.number)
s = Class1('吕耐芯', 'python1806')
s.name = '冉钊'
print(s.name)
del s.name
if __name__ == '__main__':
a0 = student1 = '张三'
a1 = student2 = '李四'
x = Class1('1806')
x.stu = [a0, a1]
print(a0, a1)
x.add(literature('王五','20', '1806'))
x.dels(a0)
网友评论