gpt4 book ai didi

python - Python 的多个构造函数

转载 作者:太空狗 更新时间:2023-10-29 20:41:18 25 4
gpt4 key购买 nike

我有一个可以通过两种不同方式生成的 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])

制作不同的 builder

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])

最佳答案

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

关于python - Python 的多个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3972333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com