Is there any way to declare class with name that I have stored in string variable in Python?
class_name = "User"
class [class_name]:
def hello():
return "world"
You can pass a string to type() and get a class back if you use the three-argument form of type.
As the docs say:
With three arguments, return a new type object. This is essentially a dynamic form of the class statement.
Now, whether this is a good solution for your problem, I'll leave up to you...
class_name = "User"
def hello(self):
return self.class_attr + " world"
AClass = type(class_name, (object,), {'class_attr': 'something', 'hello':hello})
a = AClass()
print(a)
# <__main__.User object at 0x7fc0cb29bb10>
print(a.class_attr)
# something
print(a.hello())
# 'something world'
You can use namedtuple like this:
from collections import namedtuple
class_name = "User"
a = namedtuple(class_name, "attr1, attr2, hello")
print(a) # <class '__main__.User'>
obj = a(1, 2, lambda: print("hello world!"))
print(obj) # User(attr1=1, attr2=2, hello=<function <lambda> at 0x00000241E2FA4B88>)
obj.hello() # hello world!
hello()) or change one of the attributes.hello method.
namedtuplefromcollectionsmoduleSyntaxError