在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
简单来说,把:
self.__init__(self, i)
替换成:
A(i)
这样做的原因是,init方法会改变它被调用的对象,而“self”就是当前这个对象的意思。你用构造函数(和类名是一样的)来创建一个新的对象实例。
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
对象的列表。
3
类型错误:未绑定的方法 _multiple() 必须以 A 的实例作为第一个参数(但得到了 int 的实例)
这个错误信息很直白。它的意思是你在用类的方法的方式去调用一个实例的方法。要把这个实例的方法变成类的方法,你需要加上一个叫做 @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>]
>>>