Creating an Instance of a Class with a variable in Python

后端 未结 8 1266
野性不改
野性不改 2020-12-29 05:23

I\'m trying to create a game for my little sister. It is a Virtual Pet sort of thing and the Pet has toys to play with.

I created a class Toy and want t

相关标签:
8条回答
  • 2020-12-29 05:34

    If you just want to pass a class to a function, so that this function can create new instances of that class, just treat the class like any other value you would give as a parameter:

    def printinstance(someclass):
      print someclass()
    

    Result:

    >>> printinstance(list)
    []
    >>> printinstance(dict)
    {}
    
    0 讨论(0)
  • 2020-12-29 05:35

    I think you can use eval. Something like this

    def toclass(strcls):
        return eval(strcls)()
    
    0 讨论(0)
  • 2020-12-29 05:36

    Let's say you have three classes: Enemy1, Enemy2, Enemy3. This is how you instantiate them directly:

    Enemy1()
    Enemy2()
    Enemy3()
    

    but this will also work:

    x = Enemy1
    x()
    x = Enemy2
    x()
    x = Enemy3
    x()
    

    Is this what you meant?

    0 讨论(0)
  • 2020-12-29 05:38

    You can create variable like this:

    x = 10 
    print(x)
    

    Or this:

    globals()['y'] = 100
    print(y)
    

    Lets create a new class:

    class Foo(object):
        def __init__(self):
            self.name = 'John'
    

    You can create class instance this way:

    instance_name_1 = Foo()
    

    Or this way:

    globals()['instance_name_2'] = Foo()
    

    Lets create a function:

    def create_new_instance(class_name,instance_name):
        globals()[instance_name] = class_name()
        print('Class instance '{}' created!'.format(instance_name))
    

    Call a function:

    create_new_instance(Foo,'new_instance') #Class instance 'new_instance' created!
    print(new_instance.name) #John
    

    Also we can write generator function:

    def create_instance(class_name,instance_name):
        count = 0
        while True:
            name = instance_name + str(count)
            globals()[name] = class_name()
            count += 1
            print('Class instance: {}'.format(name))
            yield True
    
    generator_instance = create_instance(Foo,'instance_') 
    
    for i in range(5):
        next(generator_instance)
    
    #out
    #Class instance: instance_0
    #Class instance: instance_1
    #Class instance: instance_2
    #Class instance: instance_3
    #Class instance: instance_4
    
    print(instance_0.name) #john
    print(instance_1.name) #john
    print(instance_2.name) #john
    print(instance_3.name) #john
    print(instance_4.name) #john
    
    #print(instance_5.name) #error.. we only created 5 instances.. 
    
    next(generator_instance) #Class instance: instance_5
    print(instance_5.name) #John  Now it works.. 
    
    0 讨论(0)
  • 2020-12-29 05:46

    Given your edit i assume you have the class name as a string and want to instantiate the class? Just use a dictionary as a dispatcher.

    class Foo(object):
        pass
    
    class Bar(object):
        pass
    
    dispatch_dict = {"Foo": Foo, "Bar": Bar}
    dispatch_dict["Foo"]() # returns an instance of Foo
    
    0 讨论(0)
  • 2020-12-29 05:46

    Rather than use multiple classes or class inheritance, perhaps a single Toy class that knows what "kind" it is:

    class Toy:
        num = 0
        def __init__(self, name, kind, *args):
            self.name = name
            self.kind = kind
            self.data = args
            self.num = Toy.num
            Toy.num += 1
    
        def __repr__(self):
            return ' '.join([self.name,self.kind,str(self.num)])
    
        def playWith(self):
            print self
    
    def getNewToy(name, kind):
        return Toy(name, kind)
    
    t1 = Toy('Suzie', 'doll')
    t2 = getNewToy('Jack', 'robot')
    print t1
    t2.playWith()
    

    Running it:

    $ python toy.py 
    Suzie doll 0
    Jack robot 1
    

    As you can see, getNewToy is really unnecessary. Now you can modify playWith to check the value of self.kind and change behavior, you can redefine playWith to designate a playmate:

    def playWith(self, who=None):
        if who:  pass
        print self
    
    t1.playWith(t2)
    
    0 讨论(0)
提交回复
热议问题