python 类的继承的实例
"""
学生:姓名/年龄/年级;吃饭/玩耍/学习
老师:姓名/年龄/职称;吃饭/玩耍/授课
"""
class Person:
def __init__(self, name, age):
"""初始化方法
:param name: 姓名
:param age: 年龄
"""
self.name = name
self.age = age
def eat(self):
"""吃饭"""
print(f'{self.name}正在吃饭.')
def play(self):
"""玩耍"""
print(f'{self.name}正在玩耍.')
class Student(Person):
"""学生"""
def __init__(self, name, age, grade):
"""初始化方法
:param grade: 年级
"""
super().__init__(name, age)
self.grade = grade
def study(self, course_name):
"""学习
:param course_name: 课程名称
"""
print(f'{self.name}正在学习{course_name}.')
class Teacher(Person):
"""老师"""
def __init__(self, name, age, title):
"""初始化方法
:param title: 职称
"""
super().__init__(name, age)
self.title = title
def teach(self, course_name):
"""授课"""
print(f'{self.name}{self.title}正在讲{course_name}.')
student = Student('lxy', 18, '大一')
teacher = Teacher('xx', 41, '博士')
student.play()
student.study('Python程序设计')
teacher.eat()
teacher.teach('数据库原理')
python 构造抽象类
from abc import ABCMeta, abstractmethod
"""
导入构造抽象类的一个类和一个方法
Employee 是一个抽象类
其中get_salary方法是一个抽象方法 继承了Employee这个类的子类都要实现这个抽象方法
子类可以重写父类的方法,不同的子类可以对同一个方法给出不同的实现版本
多态 - 不同的对象(部门经理、销售员、程序员)接收到相同的消息(get_salary)做了不同的事情(每种员工结算月薪的方式都不一样)
"""
class Employee(metaclass=ABCMeta):
def __init__(self, name):
self.name = name
@abstractmethod
def get_salary(self):
pass
class Manager(Employee):
def get_salary(self):
return 15000
class Programmer(Employee):
def __init__(self, name):
super().__init__(name)
self.working_hour = 0
def get_salary(self):
return 200 * self.working_hour
class Salesman(Employee):
def __init__(self, name):
super(Salesman, self).__init__(name)
self.sales = 0.0
def get_salary(self):
return 1800.0 + self.sales * 0.05
def main():
emps = [
Manager('lxy'), Programmer('lyq'), Programmer('xx'),
Salesman('xc'), Salesman('ww'), Programmer('hh')
]
for emp in emps:
if type(emp) == Programmer:
emp.working_hour = int(input(f'请输入{emp.name}本月工作时间: '))
elif type(emp) == Salesman:
emp.sales = float(input(f'请输入{emp.name}本月销售额: '))
print(f'{emp.name}本月工资为: {emp.get_salary():.2f}元')
if __name__ == '__main__':
main()
python 自定义一个分数类
def gcd(x, y):
"""求最大公约数"""
while y % x != 0:
x, y = y % x, x
return x
class FractionException(Exception):
"""通过继承Exception自定义异常类型 不需要写代码 主要是定义一种新的自定义类型记录异常状况"""
pass
class Fraction:
@classmethod
def from_value(cls, value):
length = len(str(value).split('.')[1])
num = int(value * 10 ** length)
den = int(1 * 10 ** length)
return cls(num, den)
@classmethod
def from_string(cls, string: str):
num, den = map(int, map(str.strip, string.split('/')))
return cls(num, den)
def __init__(self, numerator, denominator):
"""
:param numerator: 分子
:param denominator: 分母
"""
if denominator == 0:
raise FractionException("除数不能为零")
self.numerator = numerator
self.denominator = denominator
self.normalize()
self.simplify()
def simplify(self):
"""化简"""
if self.numerator != 0:
factor = gcd(abs(self.numerator), abs(self.denominator))
self.numerator, self.denominator = self.numerator // factor, self.denominator // factor
return self
def normalize(self):
"""规范化"""
if self.numerator == 0:
self.denominator = 1
elif self.denominator < 0:
self.numerator = -self.numerator
self.denominator = -self.denominator
return self
@property
def value(self):
return self.numerator / self.denominator
def __str__(self):
"""显示"""
if self.denominator == 1:
return f'{self.numerator}'
return f'{self.numerator}/{self.denominator}'
def __add__(self, other):
"""加法"""
num = self.numerator * other.denominator + other.numerator * self.denominator
den = self.denominator * other.denominator
return Fraction(num, den)
def __sub__(self, other):
"""减法"""
num = self.numerator * other.denominator - other.numerator * self.denominator
den = self.denominator * other.denominator
return Fraction(num, den)
def __mul__(self, other):
"""乘法"""
num = self.numerator * other.numerator
den = self.denominator * other.denominator
return Fraction(num, den)
def __truediv__(self, other):
"""除法"""
num = self.numerator * other.denominator
den = self.denominator * other.numerator
return Fraction(num, den)
f1 = Fraction(1, 6)
f2 = Fraction(-9, -18)
f3 = Fraction.from_string('2 / -10')
f4 = Fraction.from_value(0.52556226)
print(f1, f2)
print(f1 + f2)
print(f3)
print(f3.value)
print(f4)
|