多个构造函数与Python [英] Multiple constructor with Python

查看:186
本文介绍了多个构造函数与Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个A类,可以从两种不同的方式生成。

I have a class A that can be generated from two different ways.


  • a = A(path_to_xml_file)

  • a = A(listA,listB)

第一种方法具有文件路径作为从XML解析的输入文件获取listA和listB。第二种方法给出了两个列表。

The first method has file path as an input to parse from XML file to get listA, and listB. The second method is given two lists.

我可以想到两种方法来实现多个构造函数。你有什么感想?

I can think of two ways to implement multiple constructor. What do you think? What method normally Python guys use for this case?

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



制作不同的构建者



Make different builders

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并返回对象的工厂类方法。

Make the constructor take the two lists. Write a factory classmethod that parses the XML and returns the object.

这篇关于多个构造函数与Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆