假设我有一个类,它有一个成员叫做data,它是一个列表。

我希望能够初始化类,例如,一个文件名(包含初始化列表的数据)或一个实际的列表。

你的技巧是什么?

你只是通过查看__class__来检查类型吗?

我是不是漏掉了什么技巧?

我习惯了c++,在那里根据参数类型重载很容易。


当前回答

好了,好了。我只是用一个元组拼凑了这个例子,而不是文件名,但这很简单。谢谢所有。

class MyData:
    def __init__(self, data):
        self.myList = []
        if isinstance(data, tuple):
            for i in data:
                self.myList.append(i)
        else:
            self.myList = data

    def GetData(self):
        print self.myList

A = [1,2]

B = (2,3)

c = MyData(a)

d = MyData(b)

c.GetData()

d.GetData()

[1, 2]

[2, 3]

其他回答

你为什么不更像蟒蛇?

class AutoList:
def __init__(self, inp):
    try:                        ## Assume an opened-file...
        self.data = inp.read()
    except AttributeError:
        try:                    ## Assume an existent filename...
            with open(inp, 'r') as fd:
                self.data = fd.read()
        except:
            self.data = inp     ## Who cares what that might be?

快速和肮脏的修复

class MyData:
    def __init__(string=None,list=None):
        if string is not None:
            #do stuff
        elif list is not None:
            #do other stuff
        else:
            #make data empty

然后你可以用

MyData(astring)
MyData(None, alist)
MyData()

好了,好了。我只是用一个元组拼凑了这个例子,而不是文件名,但这很简单。谢谢所有。

class MyData:
    def __init__(self, data):
        self.myList = []
        if isinstance(data, tuple):
            for i in data:
                self.myList.append(i)
        else:
            self.myList = data

    def GetData(self):
        print self.myList

A = [1,2]

B = (2,3)

c = MyData(a)

d = MyData(b)

c.GetData()

d.GetData()

[1, 2]

[2, 3]

你应该使用isinstance

isinstance(...)
    isinstance(object, class-or-type-or-tuple) -> bool

    Return whether an object is an instance of a class or of a subclass thereof.
    With a type as second argument, return whether that is the object's type.
    The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
    isinstance(x, A) or isinstance(x, B) or ... (etc.).

在python3中,你可以像Python Cookbook中写的那样使用函数注释实现多分派:

import time


class Date(metaclass=MultipleMeta):
    def __init__(self, year:int, month:int, day:int):
        self.year = year
        self.month = month
        self.day = day

    def __init__(self):
        t = time.localtime()
        self.__init__(t.tm_year, t.tm_mon, t.tm_mday)

它是这样工作的:

>>> d = Date(2012, 12, 21)
>>> d.year
2012
>>> e = Date()
>>> e.year
2018