Python学习37天
# 魔术方法
# 创建类Monster,默认为object的子类
class Monster:
name = None
age = None
gender = None
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
# 重写魔术方法__str__输出实例对象信息
# 默认情况下调用的就是父类的object的__str__,此方法默认返回类型加地址
def __str__(self):
return f"姓名: {self.name} 年龄: {self.age} 性别: {self.gender}"
m = Monster("牛魔王", 5000, "男")
print(m)
抽象类
# 导入相关的类ABC和装饰器abstractmethod
from abc import ABC, abstractmethod
# 创建抽象类
class Employee(ABC):
# 创建构造器动态生成属性
def __init__(self, name, id, salary):
self.name = name
self.id = id
self.salary = salary
# 创建抽象方法
@abstractmethod
def work(self):
pass
class Manage(Employee):
def __init__(self, name, id, salary, bounds):
# 调用父类构造器初始化
super().__init__(name, id, salary)
# 初始化子类
self.bounds = bounds
# 完成抽象类中的抽象方法
def work(self):
print(f"经理: {self.name} id: {self.id} 年薪{self.salary * 12 + self.bounds}")
class CommonEmployee(Employee):
def work(self):
print(f"普通员工:{self.name} id: {self.id} 年薪{self.salary * 12}")
manger = Manage("tom", "10086", 20000, 40000)
manger.work()
employee = CommonEmployee("kin", "10010", 12000)
employee.work()
原文地址:https://blog.csdn.net/2301_76865484/article/details/144147287
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!