Python的多个构造函数

pro*_*eek 8 python constructor

我有一个A类,可以通过两种不同的方式生成.

  • a = A(path_to_xml_file)
  • a = A(listA,listB)

第一种方法将文件路径作为输入从XML文件解析以获取listA和listB.第二种方法有两个列表.

我可以想到两种方法来实现多个构造函数.你怎么看?通常Python人员使用什么方法来处理这种情况?

检查类型

class A():
    def __init__(self, arg1, arg2 = None):
        if isinstance(arg1, str): 
            ...
        elif isinstance(arg1, list):
            ...

a = A("abc")
b = A([1,2,3],[4,5,6])
Run Code Online (Sandbox Code Playgroud)

做不同的建设者

class A2():
    def __init__(self):
        pass
    def genFromPath(self, path):
        ...
    def genFromList(self, list1, list2):
        ...
a = A2()
a.genFromPath("abc")
b = A2()
b.genFromList([1,2,3],[4,5,6])
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 7

使构造函数取两个列表.编写一个解析XML并返回对象的工厂类方法.