Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not put self. when initializing every attribute in a Python class?

Tags:

python

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? )

like image 941
Titanio Verde Avatar asked Apr 22 '13 21:04

Titanio Verde


2 Answers

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.

like image 51
Óscar López Avatar answered Oct 11 '22 02:10

Óscar López


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"]))
like image 40
Jon Clements Avatar answered Oct 11 '22 04:10

Jon Clements