欢迎来到@一夜看尽长安花 博客,您的点赞和收藏是我持续发文的动力
对于文章中出现的任何错误请大家批评指出,一定及时修改。有任何想要讨论的问题可联系我:3329759426@qq.com 。发布文章的风格因专栏而异,均自成体系,不足之处请大家指正。
专栏:
文章概述:对Python工厂模式的介绍
关键词:Python工厂模式
本文目录:
Python工厂模式
定义一个接口,但是通过接口不能创建实例对象
from abc import ABCMeta, abstractstaticmethod
class IPerson(metaclass=ABCMeta):
@abstractstaticmethod
def person_method():
""" Interface Method """
#p1 = IPerson() #报错没有实现接口方法
#p1.person_method()
通过类实现接口
#接口实现
class Student(IPerson):
#类的初始化
def __init__(self):
self.name = 'Basic Student Name'
#接口方法的实现
def person_method(self):
print("I am a student")
class Teacher(IPerson):
def __init__(self):
self.name = 'Basic Teacher Name'
def person_method(self):
print("I am a Teacher")
s1 = Student()
s1.person_method()
t1 = Teacher()
t1.person_method()
如果我们想要创建一个Person对象,但是我们不知道是创建学生还是老师,由使用者决定的话,我们可以使用工厂模式
#创建工厂类,由别人来给出判断
class PersonFactory:
#设置为静态方法
@staticmethod
def build_person(person_type):
if person_type == 'Student':
return Student()
if person_type == 'Teacher':
return Teacher()
print("Invalid Type")
return -1
if __name__ == "__main__":
choice = input("What type of person do you want?")
person = PersonFactory.build_person(choice)
person.person_method()
解释说明:
if __name__ == "__main__":
是 Python 中一个常见的条件语句,用于判断当前模块是作为主程序运行还是被导入到其他模块中使用的。
- 作为主程序运行:
-
- 当 Python 文件直接被执行时(例如通过命令行或集成开发环境运行),Python 解释器会把该文件视为主程序。
- 在这种情况下,
__name__
的值会被设置为"__main__"
。
- 作为模块导入:
-
- 如果 Python 文件作为模块被导入到其他文件中使用,那么
__name__
的值会被设置为该模块的名称(通常是文件名去掉.py
后缀)。 - 在这种情况下,
if __name__ == "__main__":
语句的条件不成立,因此其下面的代码块不会被执行作为主程序运行时特定任务
- 如果 Python 文件作为模块被导入到其他文件中使用,那么