1.声明一个电脑类:
属性:品牌、颜色、内存大小
方法:打游戏、写代码、看视频
lass Computer:
def __init__(self,name='戴尔',color='black',age=16):
self.name = name
self.color = color
self.age = age
def playgame(self):
print('打游戏')
def write_code(self):
print('写代码')
def watch_movie(self):
print('看视频')
computer1 = Computer('联想','blue',20)
print(computer1.name)
computer1.name = '苹果'
print(computer1.name)
2.声明一个人的类和狗的类:
狗的属性:名字、颜色、年龄 狗的方法:叫唤
人的属性:名字、年龄、狗 人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Person:
def __init__(self,name='',age='',dog=''):
self.name = name
self.age = age
self.dog = dog
def walk_dog(self):
print('%s遛狗' % (self.name))
# def __str__(self):
# return '%s遛了%s' %(p1.name,dog1.name)
p1 =Person('小明',18)
print(p1.name,p1.age)
class Dog:
def __init__(self,name='',age='',color=''):
self.name = name
self.age = age
self.color = color
def bark(self):
print('%s叫了一声' % (self.name))
dog1 = Dog('大黄',10,'blue')
dog1.bark()
p1.walk_dog()
3.声明一个矩形类:
属性:长、宽 方法:计算周长和面积
a.创建不同的矩形,并且打印其周长和面积
class Rect:
def __init__(self,long = 0,width=0):
self.long =long
self.width = width
def per(self):
p = (self.long +self.width)*2
print('周长为:%d'% p )
def area(self):
a = self.long*self.width
print('面积为:%d' % a)
rect = Rect(2,3)
rect.per()
rect.area()