01
"""
1.聲明一個電腦類:
屬性:品牌、顏色彼宠、內(nèi)存大小
方法:打游戲捂刺、寫代碼、看視頻
a.創(chuàng)建電腦類的對象杠袱,然后通過對象點的方式獲取昵济、修改智绸、添加和刪除它的屬性
b.通過attr相關(guān)方法去獲取、修改访忿、添加和刪除它的屬性
"""
class Computer:
def __init__(self, brand='', color='', ram=0):
self.brand = brand
self.color = color
self.ram = ram
def video1(self):
print('看視頻')
def game1(self):
print('打游戲')
def code1(self):
print('寫代碼')
if __name__ == '__main__':
# a
com1 = Computer('DELL', '黑', 16)
print(com1.brand, com1.color, com1.ram)
com1.ram = 32
print(com1.ram)
com1.price = 1200
print(com1.price)
del com1.color
# b
print(com1.__getattribute__('ram'))
print(getattr(com1, 'brand'))
com1.__setattr__('brand', 'lenovo')
print(com1.brand)
setattr(com1, 'price', 1500)
print(com1.price)
com1.__setattr__('date', 2014)
print(com1.date)
setattr(com1, 'color', 'black')
print(com1.color)
com1.__delattr__('date')
delattr(com1, 'color')
02
"""
2.聲明一個人的類和狗的類:
狗的屬性:名字传于、顏色、年齡 狗的方法:叫喚
人的屬性:名字醉顽、年齡、狗 人的方法:遛狗
a.創(chuàng)建人的對象小明平挑,讓他擁有一條狗大黃游添,然后讓小明去遛大黃
"""
class Person:
def __init__(self, name, age, dog):
self.name = name
self.age = age
self.dog = dog
def way(self):
print('%s在遛%s' % (self.name, self.dog))
class Dog:
def __init__(self, name, age, color):
self.name = name
self.age = age
self.color = color
def way1(self):
print(('%s在叫喚', self.name))
if __name__ == '__main__':
p1 = Person('小明', 18, '大黃')
p1.way()
03
"""
3.聲明一個矩形類:
屬性:長、寬 方法:計算周長和面積
a.創(chuàng)建不同的矩形通熄,并且打印其周長和面積
"""
class Rect:
def __init__(self, width, height):
self.width = width
self.height = height
def num(self):
c = 2*(self.height + self.width)
s = self.height * self.width
print('周長為%d,面積為%d' % (c,s))
if __name__ == '__main__':
rect1 = Rect(7, 9)
rect1.num()
rect2 = Rect(5, 5)
rect2.num()
04
"""
4.創(chuàng)建一個學(xué)生類:
屬性:姓名唆涝,年齡,學(xué)號 方法:答到唇辨,展示學(xué)生信息
創(chuàng)建一個班級類:
屬性:學(xué)生廊酣,班級名 方法:添加學(xué)生,刪除學(xué)生赏枚,點名
"""
class Student:
def __init__(self, name='', age=0):
self.name = name
self.age = age
def __str__(self):
return 'name:%s,age:%d' % (self.name,self.age)
class Class:
def __init__(self,name='', students=[]):
self.name = name
self.students = students
def add_student(self):
name = input('name:')
age = int(input('age:'))
stu = Student(name,age)
self.students.append(stu)
if __name__ == '__main__':
cls1 = Class('Py1805')
cls1.add_student()
print(cls1.students[0])
05 小學(xué)語文沒學(xué)好亡驰。晓猛。。
"""
5.寫一個類凡辱,封裝所有和數(shù)學(xué)運算相關(guān)的功能(包含常用功能和常用值戒职,例如:pi,e等)
"""
class Way:
def __init__(self,type='',x=0,y=0):
self.type =type
self.x = x
self.y = y
def count(self):
if type == '+':
print('%d+%d'% (self.x, self.y))
elif type == '-':
print('%d-%d'%(self.x, self.y))
elif type == '/':
print('%d/%d'%(self.x, self.y))
elif type == '*':
print('%d*%d'%(self.x, self.y))
if __name__ == '__main__':
way1 = Way('+', 12, 32)
way1.count()