python3的类方法,指使用@classmethod进行注解的自定义方法,可以用类名直接调用。
类方法的默认参数是cls,指类本身对象,由系统自动传入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
class Factory: def __init__(self): print("工厂init==") @classmethod def createMachine(cls, clazz): if issubclass(clazz, TV): print("创建电视机") return TV("熊猫") if issubclass(clazz, Radio): print("创建收音机") return cls().__getRadio() # cls()创建类的实例对象 def __getRadio(self): return Radio() class TV: def __init__(self, brand): self.brand = brand print("电视机初始化,品牌 %s" % self.brand) def playMovie(self): print("播放电影---") class Radio: def __init__(self): print("收音机初始化") def playSong(self): print("开始广播---") tv = Factory.createMachine(TV) tv.playMovie() radio = Factory.createMachine(Radio) radio.playSong() # 创建电视机 # 电视机初始化,品牌 熊猫 # 播放电影--- # 创建收音机 # 工厂init== # 收音机初始化 # 开始广播--- |
python3的静态⽅法使用@staticmethod进行注解。无参数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class Person(object): @staticmethod #静态⽅法 def getPerson(clazz): if issubclass(clazz, Student): print("创建学生") return Student() if issubclass(clazz, Worker): print("创建工人") return Worker() class Student: def study(self): print("学习") class Worker: def work(self): print("工作") student=Person.getPerson(Student) student.study() worker=Person.getPerson(Worker) worker.work() # 创建学生 # 学习 # 创建工人 # 工作 |
-end
声明
本文由崔维友 威格灵 cuiweiyou vigiles cuiweiyou 原创,转载请注明出处:http://www.gaohaiyan.com/2663.html
承接App定制、企业web站点、办公系统软件 设计开发,外包项目,毕设