1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self, brand, color, ram):
self.brand = brand
self.color = color
self.ram = ram
def play_game(self):
print('打游戏')
def write_code(self):
print('写代码')
def read_movie(self):
print('看电影')
print('===============a===============')
c1 = Computer('联想', 'black', '8G')
print(c1.color, c1.brand, c1.ram)
c1.play_game()
c1.read_movie()
c1.write_code()
c1.color = 'yellow'
print(c1.color)
c1.rom = '1024G'
print(c1.rom)
del c1.ram
# print(jnk_computer.ram) # AttributeError: 'Computer' object has no attribute 'ram'
print('================b=================')
print('=====查======')
print(getattr(c1, 'color')) # yellow
print('======增=====')
setattr(c1, 'size', 15.6)
print(c1.size) # 15.6
print('======改=====')
setattr(c1, 'color', 'green')
print(c1.color)
print('======删=====')
delattr(c1, 'color')
# print(jnk_computer.color) # AttributeError: 'Computer' object has no attribute 'color'
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Person:
def __init__(self, name, age, dog):
self.name = name
self.age = age
self.dog = dog
def wark_dog(self):
print('{}溜{}'.format(p1.name, p1.dog))
class Dog:
def __init__(self, name, age, color):
self.name = name
self.age = age
self.color = color
def method2(self):
print('叫唤')
p1 = Person('小明', 18, 'kkk')
dog1 = Dog('大黄', 2, 'yellow')
p1.dog = dog1.name
p1.wark_dog()
3.声明⼀一个圆类,自己确定有哪些属性和方法
class Circle:
def __init__(self, radius, center_of_circle, dia):
self.dia = dia
self.radius = radius
self.center_of_circle = center_of_circle
def acreage(self):
return 3.14*self.radius**2
circle1 = Circle(2, (0, 2), 10)
print(circle1.center_of_circle, circle1.radius, circle1.dia)
print('圆面积:', circle1.acreage())
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
class Student:
def __init__(self, name, age, stu_id):
self.name = name
self.age = age
self.stu_id = stu_id
def replied(self):
print('{}报到!'.format(self.name))
def show(self):
print('name={}, age={}, stu_id={}'.format(self.name, self.age, self.stu_id))
stu1 = Student('jnk', 26, '001')
stu1.replied()
stu1.show()