1

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"
3
  • 2
    Use exec. Commented Jul 3, 2020 at 17:07
  • You can use namedtuple from collections module Commented Jul 3, 2020 at 17:09
  • 1
    @sanitizedUser But you have to check user input first. Because if it is not an appropriate class name, you might have a SyntaxError Commented Jul 3, 2020 at 17:11

2 Answers 2

3

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'
Sign up to request clarification or add additional context in comments.

Comments

1

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!

4 Comments

Some important differences between an object and a tuple will become apparent when you try to either add a method (like the OP's hello()) or change one of the attributes.
@MarkMeyer I agree it is somehow limited than classes. However, we can easily implement methods: see my update. I added hello method.
You've added a static function, not a method. A method would allow you to use the state of the object — for example to print one of the attributes or to sum the attributes, etc...
@MarkMeyer Yes I agree, but we can emulate a method by defining a lambda function with 1 parameter. And whenever we call it, we give to it the object. It is not like real class, but it might work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.