Greetings.
I searched for a long time, and found many related questions with no answer for me. Despite mine seems to be a simple beginner doubt.
We have a (I guess) typical class definition:
class Town:
def __init__(self, Name, Ruler = "Spanish Inquisition"):
self.Name = Name
self.Population = 0
self.LocationX = 0
self.LocationY = 0
self.Religion = "Jedi"
self.Ruler = Ruler
self.Products = ["Redstone", "Azaleas"]
You get the idea. A lot of attributes. I need all of them.
The question is: **Is there a shortcut to save all those "self."?** Am I being too lazy? I hoped for something like:
with self:
Name = Name
Population = 0
...
which of course I know does not work (this is not the use of "with", and arguments are in a wrong namespace. ... I got it right?).
I guess there are a lot of alternatives to achieve the same result, but I'm really curious about the power of Python classes, and I think other people asked about this with no success.
(A related question: Most "pythonic" way of organising class attributes, constructor arguments and subclass constructor defaults? )
Short answer: no, you can't. It's mandatory to use self
when accessing an instance member (attribute, method) in Python.
A clarification: self
is not a keyword in Python. In principle you could give the first parameter of a method any name, but convention mandates that you should call it self
.
You won't make any friends, but one way....:
class Town2:
def __init__(self, name, ruler = 'Spider Pig'):
self.__dict__.update(dict(
Name = name,
Population = 0,
LocationX = 0,
LocationY = 0,
Religion = "Jedi",
Ruler = ruler,
Products = ["Redstone", "Azaleas"]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With