For classes and objects in Python | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 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'?

4th Feb 2017, 9:47 PM
Iago MuƱoz Varela
Iago MuƱoz Varela - avatar
8 Respostas
+ 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.
5th Feb 2017, 12:02 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 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!
5th Feb 2017, 7:19 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 2
In that case you only need: class GameObject: def __init__(self, name): self.name = name elf = GameObject("elf") print (elf.name) >>> elf
5th Feb 2017, 6:28 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 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.
5th Feb 2017, 6:17 PM
DotJason
0
yeah that is basically what I wanted to say... thanks for replying I hope I can find some way to do that sometime :)
5th Feb 2017, 4:51 PM
Iago MuƱoz Varela
Iago MuƱoz Varela - avatar
0
Damn, thanks
5th Feb 2017, 6:21 PM
Iago MuƱoz Varela
Iago MuƱoz Varela - avatar
0
It was not that xD but thank you, that gave me some ideas
5th Feb 2017, 7:38 PM
Iago MuƱoz Varela
Iago MuƱoz Varela - avatar
0
Hola
6th Feb 2017, 6:02 PM
Ramdom06 crafteano
Ramdom06 crafteano - avatar