在Python中的同一个类中创建多个对象

时间:2013-01-30 09:33:27

标签: python

我希望能够通过使用类中的方法返回类的多个对象。这样的事情。

class A:
    def __init__(self,a):
    self.a = a

    def _multiple(self,*l):
        obj = []
        for i in l:
            o = self.__init__(self,i)
            obj.append(o)
        return obj

当我在iPython(iPython 0.10和Python 2.6.6)上执行此操作时,我得到以下内容

In [466]: l = [1,2]
In [502]: A._multiple(*l)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

TypeError: unbound method _multiple() must be called with A instance as 
first argument (got int instance instead)

我绝对不清楚调用以及'self'关键字的使用情况。你能帮我解决这个问题吗?

谢谢。

3 个答案:

答案 0 :(得分:2)

  

TypeError:必须使用A实例调用未绑定方法_multiple()   作为第一个参数(改为使用int实例)

错误是自我解释的。这意味着实例方法被称为Class方法。要将实例方法作为类方法,请添加装饰器@classmethod

>>> class A:
    def __init__(self,a):
        self.a = a
    @classmethod
    def _multiple(cls,*l):
        #Create multiple instances of object `A`
        return [A(i) for i in l]

>>> l = [1,2]
>>> A._multiple(*l)
[<__main__.A instance at 0x066FBB20>, <__main__.A instance at 0x03D94580>]
>>> 

答案 1 :(得分:1)

你想要一个类方法:

class A:
    def __init__(self,a):
        self.a = a

    @classmethod
    def _multiple(cls,*l):
        obj = []
        for i in l:
            o = cls(i)
            obj.append(o)
        return obj


>>> A._multiple(1, 2) # returns 2 A's
[<__main__.A instance at 0x02B7EFA8>, <__main__.A instance at 0x02B7EFD0>]

classmethod装饰器将通常的self替换为第一个参数,并引用该类(在本例中为A)。请注意,这样做意味着如果你继承A并在子类上调用_multiple,它将被传递给子类。

class B(A): pass

>>> B._multiple(1, 2, 3)
[<__main__.B instance at 0x02B87C10>, <__main__.B instance at 0x02B87D28>, <__main__.B instance at 0x02B87CD8>]

会创建B个对象的列表。

答案 2 :(得分:0)

简单地替换:

 self.__init__(self, i)

使用:

 A(i)

原因是init方法改变了调用它的对象,“self”是当前实例。您可以使用构造函数(与类同名)来创建新实例。

相关问题