"""author = 曹琦"""
1.声明一个电脑类: 属性:品牌、颜色、内存大小 方法:打游戏、写代码、看视频
class Computer:
def __init__(self,brand1='华硕',color1='黑色',memory_size1 = '500G'):
self.brand = brand1
self.color = color1
self.memory_size = memory_size1
def play_game(self):
print('打游戏')
def write_code(self):
print('写代码')
def watch_video(self):
print('看视频')
# a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
print('====第1题a=====')
a1 = Computer()
print(a1.brand)
a1.brand = '神舟'
print(a1.brand)
a1.price = 5000
print(a1.price)
del a1.price
# print(a1.price) # AttributeError: 'Computer' object has no attribute 'price'
# b.通过attr相关方法去获取、修改、添加和删除它的属性
print(getattr(a1,'brand','华硕'))
setattr(a1,'color','白色')
print(a1.color)
delattr(a1,'memory_size')
# print(a1.memory) # AttributeError: memory_size
2.声明一个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的方法:叫唤
人的属性:名字、年龄、狗
人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Person:
def __init__(self,name,age,dog):
self.name = name
self.age = age
self.dog = dog
def work_dog(self):
return '%s溜%s' % (self.name,self.dog)
class Dog:
def __init__(self,name,color,age):
self.name1 = name
self.color1 = color
self.age1 = age
def bark(self):
return 'wangWang'
dog1 = Dog('大黄','黄色','3')
person1 = Person('小明','20',dog1.name1)
print(person1.work_dog())
3.声明一个圆类,自己确定有哪些属性和方法
import math
class Circle:
def __init__(self,radius):
self.radius = radius
def diameter(self):
return self.radius*2
def perimeter(self):
return self.radius*2*math.pi
def area(self):
return self.radius*math.pi*self.radius
a4 = Circle(2)
print(a4.diameter())
print(a4.perimeter())
print(a4.area())