0

I have the below sample code:

def sample(cls):
    class a():
        def __init__(self):
            self.value='a'
    class b():
        def __init__(self):
            self.value='b'
    def __init__(self):
       self.cls=cls()
    return self.value

sample(b)

I have defined 2 classes in the sample code. I want to be able to define the class name in a function. So the above code will return 'b'. Is there a way to do it? The above code will give me the error:

'str' object is not callable

Tornar
  • 35
  • 6
  • What's the use case and aside from that are there syntax errors in your code. Can you please add more information to your question? :) – Tom Feb 15 '22 at 22:54
  • You can't literally pass the class name, because the class names are not defined outside of the function. You could pass a string, and do `if cls=='a':` / `return a()` / `else:` / `return b()`, or even have a dictionary to do the mapping. – Tim Roberts Feb 15 '22 at 22:56
  • 1
    What about `__name__` to get the [class name of the instance](https://stackoverflow.com/questions/510972/getting-the-class-name-of-an-instance)? – hc_dev Feb 15 '22 at 22:58

1 Answers1

0

This is one option:

def sample(cls):
    class a():
        def __init__(self):
            self.value='a'
    class b():
        def __init__(self):
            self.value='b'
    return {'a': a, 'b': b}[cls]()

print(sample('b'))

Or, if you really want to use the class name, you could define the classes outside of the function:

class a():
    def __init__(self):
        self.value='a'
class b():
    def __init__(self):
        self.value='b'

def sample(cls):
    return cls()

print(sample(b))

Not sure what the advantage would be over just calling b().

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Thanks, this works. Writing the class outside of the function is a better approach to this. – Tornar Feb 16 '22 at 07:45