假设我有一个类,其成员名为data,这是一个列表。

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

你这样做的技巧是什么?

您只是通过查看 __ class __

来检查类型

我可能会遗漏一些技巧吗?

我习惯于使用参数类型重载的C ++很容易。

有帮助吗?

解决方案

获得'替代构造函数'的更简洁方法是使用类方法。例如:

>>> class MyData:
...     def __init__(self, data):
...         "Initialize MyData from a sequence"
...         self.data = data
...     
...     @classmethod
...     def fromfilename(cls, filename):
...         "Initialize MyData from a file"
...         data = open(filename).readlines()
...         return cls(data)
...     
...     @classmethod
...     def fromdict(cls, datadict):
...         "Initialize MyData from a dict's items"
...         return cls(datadict.items())
... 
>>> MyData([1, 2, 3]).data
[1, 2, 3]
>>> MyData.fromfilename("/tmp/foobar").data
['foo\n', 'bar\n', 'baz\n']
>>> MyData.fromdict({"spam": "ham"}).data
[('spam', 'ham')]

它更整洁的原因是毫无疑问预期会出现什么类型,并且您不必猜测调用者打算如何处理它为您提供的数据类型。 isinstance(x,basestring)的问题在于,调用者无法告诉您,例如,即使类型不是基本字符串,您也应该将其视为字符串(并且可能呼叫者想要将相同类型用于不同目的,有时作为单个项目,有时作为一系列项目。明确表达了所有怀疑并导致更强大和更清晰的代码。

其他提示

很好的问题。我也解决了这个问题,虽然我同意“工厂”这个问题。 (类方法构造函数)是一个很好的方法,我想建议另一个,我也发现它非常有用:

这是一个示例(这是一个 read 方法而不是构造函数,但想法是一样的):

def read(self, str=None, filename=None, addr=0):
    """ Read binary data and return a store object. The data
        store is also saved in the interal 'data' attribute.

        The data can either be taken from a string (str 
        argument) or a file (provide a filename, which will 
        be read in binary mode). If both are provided, the str 
        will be used. If neither is provided, an ArgumentError 
        is raised.
    """
    if str is None:
        if filename is None:
            raise ArgumentError('Please supply a string or a filename')

        file = open(filename, 'rb')
        str = file.read()
        file.close()
    ...
    ... # rest of code

关键的想法是使用Python对命名参数的出色支持来实现它。现在,如果我想从文件中读取数据,我说:

obj.read(filename="blob.txt")

要从字符串中读取它,我说:

obj.read(str="\x34\x55")

这样用户只需一个方法即可调用。如你所见,在里面处理它并不是太复杂

快速而肮脏的修复

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

更好的方法是使用isinstance和类型转换。如果我理解你,你想要这个:

def __init__ (self, filename):
    if isinstance (filename, basestring):
        # filename is a string
    else:
        # try to convert to a list
        self.path = list (filename)

使用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

您应该使用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.).

你可能想要 isinstance 内置函数:

self.data = data if isinstance(data, list) else self.parse(data)

我首选的解决方案是:

class MyClass:
    _data = []
    __init__(self,data=None):
        # do init stuff
        if not data: return
        self._data = list(data) # list() copies the list, instead of pointing to it.

然后使用 MyClass() MyClass([1,2,3])调用它。

希望有所帮助。快乐的编码!

好的,太好了。我只是用一个元组而不是文件名将这个例子拼凑在一起,但这很容易。谢谢大家。

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]

你为什么不去更加pythonic?

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?
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top