Creating multiple objects within the same class in Python

python

Solution

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

The Error is self explanatory. It means that an instance method is being called as a Class method. To make the instance method as a class method add the decorator `@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>]
>>> 

Problem

I want to be able to return multiple objects of a class by using a method within the class. Something like this. ``` 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 ``` When I execute this on iPython (iPython 0.10 and Python 2.6.6) I get the following ``` 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) ``` I'm definitely unclear about the invocation as well as the 'self' keyword usage. Could you help me out in getting this correct? Thank you.

Original source