1.声明一个电脑类:
属性:品牌、颜色、内存大小
方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关方法去获取、修改、添加和删除它的属性
class Computer:
__slots__ = ('brand', 'color', 'memory')
def __init__(self, brand='Asus', color='Pink', memory='8G'):
self.brand = brand # 商标
self.color = color # 颜色
self.memory =memory # 内存
@staticmethod
def play_computer_games():
print('LOL、DOTA2、PUBG、逆水寒都可以玩')
@staticmethod
def coding():
print('Coding makes perfect .')
@staticmethod
def watch_videos():
print('Also can watch videos')
c1 = Computer()
print(c1.brand, c1.color, c1.memory)
c1.color = 'Blank'
print(c1.brand, c1.color, c1.memory)
c1.price = 4999
print(c1.brand, c1.color, c1.memory, c1.price)
del c1.color
getattr(c1, 'brand')
delattr(c1, 'price')
setattr(c1, 'weight', '2.5kg')
Output:
Asus Pink 8G
Asus Blank 8G
Asus Blank 8G 4999
2.声明一个人的类和狗的类:
狗的属性:名字、颜色、年龄 狗的方法:叫唤
人的属性:名字、年龄、狗 人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Person:
__slots__ = ('name', 'age', 'dog')
def __init__(self, name, age, dog):
self.name = name
self.age = age
self.dog = dog
def walking_dog(self):
print('%s正在遛%s' % (self.name, self.dog))
class Dog:
__slots__ = ('name', 'color', 'age')
def __init__(self, name, color, age):
self.name = name
self.color = color
self.age = age
@staticmethod
def bark():
return
d1 = Dog('大黄', 'yellow', '7')
p1 = Person('小明', '22', d1)
p1.walking_dog()
3.声明一个矩形类:
属性:长、宽 方法:计算周长和面积
a.创建不同的矩形,并且打印其周长和面积
class Rect:
def __init__(self, width, height):
self.width = width
self.height = height
def girth(self):
return (self.width + self.height) * 2
def area(self):
return self.width * self.height
rect1 = Rect(13, 21)
girth = rect1.girth()
area = rect1.area()
print('宽度高度分别%d、%d矩形的周长是:%d, 面积是:%d' % (rect1.width, rect1.height, girth, area))
rect2 = Rect(7, 9)
girth = rect1.girth()
area = rect1.area()
print('宽度高度分别%d、%d矩形的周长是:%d, 面积是:%d' % (rect2.width, rect2.height, girth, area))
4.创建一个学生类:
属性:姓名,年龄,学号 方法:答到,展示学生信息
创建一个班级类:
属性:学生,班级名 方法:添加学生,删除学生,点名
class Student:
def __init__(self, name, age, id):
self.name = name
self.age = age
self.id = id
def display(self):
print('姓名:%s,年龄:%d,学号:%s' % (self.name, self.age, self.id))
def reply(self):
print(self.name + '到!')
class Class:
def __init__(self, name, students=[]):
self.name = name
self.students = students
def add_student(self):
name = input('name:')
age = input('age:')
stu_id = input('id:')
stu = Student(name, int(age), stu_id)
self.students.append(stu)
def del_student(self):
return
def call(self):
return
cls1 = Class('py1805', [])
cls1.add_student()
students = cls1.students
stu = students[0]
print(stu.name)
5.写一个类,封装所有和数学运算相关的功能(包含常用功能和常用值,例如:pi,e等)
class MathOperation:
pi = 3.1415926
e = 2.71828
@staticmethod
def add(a, b):
return a + b
@staticmethod
def sub(a, b):
return a - b
@staticmethod
def mul(a, b):
return a * b
@staticmethod
def dev(a, b):
return a / b
网友评论