声明一个电脑类:
属性:品牌、颜色、内存大小
方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关方法去获取、修改、添加和删除它的属性
class Compter:
def __init__(self,brand="lenovo",color="black",memory=24):
self.brand = brand
self.color = color
self.memeory = memory
def palygame(self):
print('打游戏')
def playcode(self):
print('写代码')
def watchTV(self):
print('看电视')
#创建一个对象
com1 = Compter()
#查看对象的属性
print(com1.brand)
print(getattr(com1,'brand'))
#修改对象的属性
com1.brand ='apple'
print(com1.brand)
setattr(com1,'brand','apple')
print(com1.brand)
#添加对象的属性
com1.ram='8G'
print(com1.ram)
setattr(com1,'rom','1T')
print(com1.rom)
#删除对象属性
del com1.memeory
# print(com1.memeory) #AttributeError: 'Compter' object has no attribute 'memeory'
delattr(com1,'color')
# print(com1.color) #AttributeError: 'Compter' object has no attribute 'color'
lenovo
lenovo
apple
apple
8G
1T
声明一个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的方法:叫唤
人的属性:名字、年龄、狗
人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Dog:
def __init__(self,name='大黄',color='',age=0):
self.name = name
self.age = age
self.color = color
def cry(self):
print('叫唤')
class Person:
def __init__(self,name='',age=0,dog=''):
self.name = name
self.age = age
self.dog =dog
def walk_the_dog(self,dog):
dog = Dog()
print('%s去遛%s'%(self.name,dog.name))
d1 = Dog('大黄')
p1 = Person('小明')
p1.walk_the_dog(d1)
小明去遛大黄
声明一个矩形类:
属性:长、宽
方法:计算周长和面积
a.创建不同的矩形,并且打印其周长和面积
class Rectangle:
def __init__(self,w=0,h=0,):
self.w = w
self.h = h
def print_S_C(self,w,h):
S = w * h
H = 2 * (w + h)
print(S,H)
rec1 = Rectangle(3,4)
rec1.print_S_C(3,4)
12 14
写一个类,封装所有和数学运算相关的功能(包含常用功能和常用值,例如:pi, e等)
class Run:
def pi(self):
return 3.1415926
def e(self):
return 2.14
pi = Run().pi()
e = Run().e()
print(2*pi-4)
print(2**e)
2.2831852
4.4076204635064435
6.1.写一个班级类,属性:班级名、学生;功能:添加学生、删除学生、根据姓名查看学生信息,展示班级的所有学生信息
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.calss_name = name
self.students = students
def add_student(self):
name = input('name:')
age = input('age:')
#根据创建的信息创建学生对象
stu = Student(name,int(age))
#添加学生
self.students.append(stu)
#创建类的对象
cls1 = Class('py1801')
cls1.add_student()
print(cls1.students[0]) #cls1.students还是一个对象
name:222
age:222
name:222 age:222
网友评论