+ 2
For classes and objects in Python
How can i use a variable's value which is a string to take that string to make a class with the name of the strinng itself. For example: I have defined a superclass named GameObject, where I have a dictionary (named objects) with the existing objects. Now I want to externally create a new object with the function create(noun) where noun='elf' for example. So, how con I do something like this: def create(noun): if noun in GameObject.objects: class "noun"(GameObject): etc... etc... The question is: how can I do to transform that "noun" into 'elf'?
8 odpowiedzi
+ 3
I can't grasp the idea... You want to create a class on-the-fly during the program? I don't think it can be done...
But your question seems to me you really want to instantiate an object with a given name attribute. That can be done easily ;)
Pls elaborate more on the issue.
+ 3
Alright, now I think I get what you mean :)
class GameObject:
attack = " attacks!"
def __init__(self, name):
self.name = name
def attacks(self):
return self.name + self.attack
class Elf(GameObject):
def __init__(self):
self.name = "Elf"
self.attack = " shoots an arrow!"
class Dwarf(GameObject):
def __init__(self):
self.name = "Dwarf"
self.attack = " hacks with an axe!"
Llewellyn = Elf()
Rolf = Dwarf()
print (Llewellyn.attacks())
print (Rolf.attacks())
>>>
Elf shoots an arrow!
Dwarf hacks with an axe!
+ 2
In that case you only need:
class GameObject:
def __init__(self, name):
self.name = name
elf = GameObject("elf")
print (elf.name)
>>>
elf
+ 1
well, a good question I have been interested in myself.
In short: there's no way to do it (and there shouldn't be one).
Instead, making class instances makes much more sense, as classes, although being something you can create anywhere, are not designed for mass-production, unlike instances. If your many classes you are trying to produce all have same fields and methods (and they do, as I can see), then inheriting from GameObject once and then instancing that class is your solution I suppose.
0
yeah that is basically what I wanted to say... thanks for replying I hope I can find some way to do that sometime :)
0
Damn, thanks
0
It was not that xD but thank you, that gave me some ideas
0
Hola