1.聲明?個電腦類: 屬性:品牌辑畦、顏?吗蚌、內存?小 方法:打游戲、寫代碼纯出、看視頻
class Computer:
def __init__(self,brand,color,memsize):
self.brand = brand
self.color = color
self.memsize = memsize
def PlayGame(self):
return '打游戲'
p1 = Computer('聯(lián)想','藍色','8G')
print(p1.PlayGame())
a.創(chuàng)建電腦類的對象蚯妇,然后通過對象點的?方式獲取、修改暂筝、添加和刪除它的屬性
class Computer:
def __init__(self,brand,color,memsize):
self.brand = brand
self.color = color
self.memsize = memsize
p1 = Computer('聯(lián)想','藍色','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('聯(lián)想','藍色','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.創(chuàng)建?人的對象?小明务漩,讓他擁有?一條狗?大?黃拄衰,然后讓?小明去遛?大?黃
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.創(chuàng)建?一個學?生類:
屬性:姓名,年齡菲饼,學號
方法:答到肾砂,展示學?生信息
創(chuàng)建?一個班級類:
屬性:學?生列赎,班級名
方法:添加學?生宏悦,刪除學生,點名, 求班上學生的平均年齡