P133 Class对象和静态方法
1. Class对象
1.1 基本介绍
1) 文档: https://docs.python.org/zh-cn/3.12/tutorial/classes.html#class-objects
2) 类本身也是对象,即class对象
1.2 应用实例
class Monster:
name = "蝎子精"
age = 300
def hi(self):
print(f'hi(){self.name}-{self.age}')
print(Monster)
print(f"Monster.name:{Monster.name} Monster.age:{Monster.age}")
Monster.hi(Monster)
print("*" * 32)
2. 静态方法
2.1 基本介绍
1) 文档: https://docs.python.org/zh-cn/3.12/library/functions.html#staticmethod
2) @staticmethod 将方法转换为静态方法
3) 静态方法不回接受隐式的第一个参数,要声明一个静态方法,语法:
class C:
@staticmethod
def f(arg1,arg2,argN): ...
4) 静态方法既可以由类调用(如C.f()),也可以由实例中调用(如C().f())
2.2 应用介绍
class Monster:
name ="揭子精"
age = 300
def hi(self):
print(f'hi() {self.name}-{self.age}')
@staticmethod
def ok():
print("ok()...")
Monster.ok()
monster = Monster()
monster.ok()
P134 抽象类
1.问题引出
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/29f35e3f70f74ebb9831119d5bd7e85a.png)
2.快速入门
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/2c41d8f0857e4ca29625f29249931fb0.png)
from abc import ABC, abstractmethod
class Animal(ABC):
def __init__(self, name, age):
self.name = name
self.age = age
@abstractmethod
def cry(self):
pass
class Tiger(Animal):
def cry(self):
print(f"牢虎{self.name} 嗷嗷叫...")
tiger = Tiger("毛毛",10)
tiger.cry()
P135 抽象类的注意事项和细节
1. 注意事项和使用细节
- 抽象类不能被实例化
- 抽象类需要继承ABC,并且需要至少一个抽象方法
from abc import ABC, abstractmethod
class AAA(ABC):
name = "tim"
@abstractmethod
def f1(self):
pass
obj1 = AAA()
print("ok")
- 抽象类可以有普通方法
from abc import ABC, abstractmethod
class AAA(ABC):
name = "tim"
@abstractmethod
def f1(self):
pass
def hi(self):
print("hi()~~")
def ok(self):
pass
class BBB(AAA):
def f1(self):
print("BBB - f1()...")
obj2 = BBB()
obj2.ok()
obj2.f1()
obj2.hi()
print("~~")
- 如果一个类继承了抽象类,则它必须实现抽象类的所有抽象方法,否则它仍然是一个抽象类
from abc import ABC, abstractmethod
class AAA(ABC):
name = "tim"
@abstractmethod
def f1(self):
pass
@abstractmethod
def f2(self):
pass
def hi(self):
print("hi()~~")
def ok(self):
pass
class BBB(AAA):
def f1(self):
print("BBB - f1()...")
def f2(self):
print("BBB - f2()...")
obj2 = BBB()
obj2.ok()
obj2.f1()
obj2.hi()
print("~~")
from abc import ABC, abstractmethod
class Employee(ABC):
name = "tim"
id = None
salary = None
def __init__(self,name,id,salary):
self.name = name
self.id = id
self.salary = salary
@abstractmethod
def work(self):
pass
class CommonEmployee(Employee):
def work(self):
print(f"普通员工{self.name} 正在工作中...")
class Manager(Employee):
bonus = None
def __init__(self, name, id, salary,bonus):
super().__init__(name, id, salary)
self.bonus = bonus
def work(self):
print(f"经理{self.name} 正在工作中...")
com = CommonEmployee("小张",10,2000)
com.work()
mana = Manager("王总",1,20000,120000)
mana.work()