1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小
方法: 打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self, brand: str, color: str, storage=0):
self.brand = brand
self.color = color
self.storage = storage
def play(self,game):
print('玩儿%s' % game)
@staticmethod
def write(self):
print('用%s写代码' % self.brand)
@staticmethod
def see(self):
print('看%s' % video)
def main():
# a.
c1 = Computer('三星', '白色', '8G')
c2 = Computer('苹果', '黑色', '16G')
print(c1.brand, c1.color, c1.storage)
c2.color = '蓝色'
print(c2.brand, c2.color, c2.storage)
print(getattr(c1,'storage',13))
print(setattr(c1, 'weight', 200))
print(c1.weight)
del c1.brand
delattr(c2,'color')
print(getattr(c2,'color',None))
2.声明⼀个人的类和狗的类:
狗的属性: 名字、颜⾊色、年年龄
狗的⽅方法: 叫唤
人的属性: 名字、年年龄、狗
人的⽅方法: 遛狗
创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Dog:
def __init__(self, name, color, age):
self.name = name
self.color = color
self.age = age
def bark(self):
return 'wang!wang!wang!'
def main():
p1 = Person('小明', 18)
class Person:
def __init__(self, name='', age=0,dog:Dog=None):
self.name = name
self.age = age
self.dog = dog
def playDog(self):
if self.dog:
print('%s牵着%s在外面散步' % (self.name,
self.dog.name))
else:
print('没有🐶!遛自己!')
3.声明⼀一个圆类:
class YTValueError(Exception):
def __init__(self):
return '输入错误'
class circle:
pi=3.14159265357
def __init__(self, x: float, y: float, r: float):
self.x = x
self.y = y
self.r = r
self._area=0
self._perimeter=0
@property
def area(self):
return self.r**2*Circle.pi
@area.setter
def area(self,value):
raise YTValueError
def area(self):
return self.r**2*Circle.pi
def perimetrer(self):
return 2*Circle.pi*Circle.r
4.创建一个学生类:
属性: 姓名,年龄,学号
方法: 答到,展示学生信息
``
class Student:
def init(self, name, age, number):
self.name = name
self.age = age
self.number = number
def method(self):
return '答到'
def method1(self):
return '展示信息'
class Class:
stu = []
def __init__(self, student, class_name):
self.student = student
self.class_name = class_name
@classmethod
def add_student(self):
print('添加学生!')
Student.name=input('姓名:')
Student.age=input('年龄:')
print(Class.stu)
@classmethod
def del_student(self):
d = input('删除学生')
Class.stu.remove(d)
print(Class.stu)
创建⼀一个班级类:
属性: 学生,班级名
方法: 添加学生,删除学生,点名, 求班上学生的平均年龄
网友评论