1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
class Computer:
def __init__(self,brand,color,memsize):
self.brand = brand
self.color = color
self.memsize = memsize
def PlayGame(self):
return '打游戏'
p1 = Computer('联想','蓝色','8G')
print(p1.PlayGame())
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
class Computer:
def __init__(self,brand,color,memsize):
self.brand = brand
self.color = color
self.memsize = memsize
p1 = Computer('联想','蓝色','8G')
print(p1.brand)
print(p1.color)
print(p1.memsize)
p1.brand = '神舟'
print(p1.brand)
p1.size = 15.6
print(p1.size)
del p1.size
print(p1.size) #AttributeError: 'Computer' object has no attribute 'size'
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self,brand,color,memsize):
self.brand = brand
self.color = color
self.memsize = memsize
p1 = Computer('联想','蓝色','8G')
print(getattr(p1,'brand'))
print(getattr(p1,'color'))
setattr(p1,'color','红色')
print(getattr(p1,'color'))
setattr(p1,'size',15.6)
print(getattr(p1,'size'))
delattr(p1,'size')
getattr(p1,'size') #AttributeError: 'Computer' object has no attribute 'size'
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Dog:
def __init__(self,name,color,age):
self.name = name
self.color = color
self.age = age
def jiaohuan(self):
return '汪汪汪'
p1 = Dog('大大黄黄','黄色',1)
# p2 = Person('小小明',)
class Person:
def __init__(self,name,age,dog):
self.name = name
self.age = age
self.dog = dog
def fangfa(self):
return ('%s遛%s'% (self.name,self.dog))
p2 = Person('小小明',18,p1.name)
print(p2.fangfa())
3.声明⼀一个圆类:
import math
class Garden:
def __init__(self,r):
self.r = r
def area(self):
return (math.pi) * self.r ** 2
def perimeter(self):
return (math.pi) * self.r * 2
p1 = Garden(3)
print(p1.area())
print(p1.perimeter())
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
网友评论