+ 1

Class names

Is it possible to have the name of a class as a variable? Like if I wanted the class to be whatever the user inputted. Like if x = “obj” and I have x = class(self). Would that work at all? If not, could it work in a different way?

25th Apr 2022, 5:30 PM
StrWrsBoi
StrWrsBoi - avatar
5 Antworten
+ 6
I can think of a way to do it, however I would very much prefer if it were not used, as it is a method to be used very sparingly and is probably not the most efficient way. That said, there is a function exec(). What you can do is use an f string as a parameter. So let us say you want to make a simple class, let's say with just a constructor, that initialises the value of the age. In normal python we have: class class_name: def __init__(self,age): self.age = age Right, so this is our code, with class_name our input. With exec it is (beware it is all one line with escape characters): className = input() exec(f'class {className}:\n def __init__(self,age):\n self.age = age') then you may do whatever afterwards. Two words of warning: a) mind the indentations after the escape characters are just like normal, imagine the \n as pressing enter, everything else is the same b) This IS NOT inline with pythonicness (unless very short). I don't believe you have covered this in your courses (you might have elsewhere), but have a little check at pep, particularly pep 8 (I'm a python purist as you see!) Take that last warning as you wish, I'm really just here to help :) Happy coding! EDIT: Here's a link to PEP 8 if you want to have a look: https://peps.python.org/pep-0008/
25th Apr 2022, 6:45 PM
Kamil Hamid
Kamil Hamid - avatar
+ 4
StrWrsBoi , what advantage do you expect from this procedure? have you done a try so far that you can LINK for us here ? thanks!
25th Apr 2022, 5:47 PM
Lothar
Lothar - avatar
+ 3
You can store your classes in a dict under a name and access it via the key. classes = { 'Class1': Class1, 'Class2': Class2 } x = input('Class1 or Class2?') obj = classes[x]() (Normally, when the user is to interact with data like that, you'd use a dict - or other container types depending on the case. Exec is something you try hard not to touch. ;))
26th Apr 2022, 11:52 AM
HonFu
HonFu - avatar
26th Apr 2022, 9:52 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 1
Hi! When you tried, what was your reflection?
25th Apr 2022, 5:48 PM
Per Bratthammar
Per Bratthammar - avatar