-1

I want to be able to set the instance variable name in a Python class based on an argument in __init__. Is this possible? Below is what I've tried but that doesn't work.

class my_class:
  def __init__(self, var_name):
    self['var' + var_name] = var_name
Gaurav Bansal
  • 5,221
  • 14
  • 45
  • 91
  • 1
    Don't do that. It's just not good practice to create names on the fly. Instead, use a dictionary. That's exactly what they were designed for. – Tim Roberts Nov 19 '21 at 20:11
  • What are you trying to accomplish exactly? What's the context? When you say "variable name", that makes me think [*identifier*](https://docs.python.org/3/reference/lexical_analysis.html#identifiers), but your code uses a [*subscription*](https://docs.python.org/3/reference/expressions.html#subscriptions), and it sort of sounds like you're actually talking about an [*attribute*](https://docs.python.org/3/reference/expressions.html#attribute-references). Please [edit] to clarify. – wjandrea Nov 19 '21 at 20:25
  • Possibly related: [How do I create variable variables?](/q/1373164/4518341) – wjandrea Nov 19 '21 at 20:26

1 Answers1

2

Something like the below.

(Question: why do you want to do that?)

class MyClass:
  def __init__(self, var_name):
    setattr(self,var_name,var_name)

c = MyClass('jack')
print(c.jack)

output

jack
balderman
  • 22,927
  • 7
  • 34
  • 52