As @florian said you would need some monster hacks to pull this off which would end up being way more complicated than just passing in the name as a string. But, let me explain why it requires hacks:
- You assign Lahore to city(“LHE”, “Punjab”, “PJB”)
- This calls the
city.__init__
function.
- Now, imagined you’re right at the first line of that function: self.abb. Ask yourself, how does that line get access to your variable Lahore?
See how “self.abb” is deep inside class city, and then __init__
? That puts it in a different context, and you’d need to be able to somehow “reach” outside of that, and then get at that variable name Lahore. But, it doesn’t stop with that.
When you read this line you read it backwards from what the computer does. Let’s read it:
Lahore = city("LHE", "Punjab", "PJB")
Humans read that as:
“Lahore equals city parens double quote LHE double quote comma Punjab double quote comma double quote PJB double quote parens”
BUT, Python process this basically backwards:
Lahore = city("LHE", "Punjab", "PJB")
Is actually processed:
- Create “LHE” string
- Create “Punjab” string
- Create “PJB” string
- Create tuple of 1-3.
- Find
city.__init__
- Call
city.__init__
with tuple from 4.
- Take result from
city.__init__
and THEN create Lahore variable.
- Assign Lahore to
city.__init__
results.
If you follow these steps (which are approximate, not exactly what Python does) then you can see that the variable Lahore doesn’t even exist until after __init__
is all done.
Finally, there’s this kind of odd compulsion in programming where you’ll want to try to code away repetition. You’ll say, “I keep typing Lahore twice so why not make the 2nd one go away by getting the variable name?”
Then you go down that path and realize that the amount of code and the complexity involved in this is far beyond just doing:
self.name = name
So you’re not actually improving anything. At that point, repetition is far superior to trying to remove it since the more direct and simple self.name = name
will always perform better, have fewer bugs, and be easier to change and understand later.