Search code examples
pythonvariablesinitializationshortcutself

Python: convenient way to initialize lots of class members


If I have lots of class variables to initialize, any way to shorten the use of "self." ? That is, instead of doing:

self.variable1 = 1
self.variable2 = 10
self.variable3 = "hello"
etc.

is it possible to do some shortcut like:

with self: 
    variable1 = 1
    variable2 = 2
    variable3 = 'hello'

Just thought I could save on some typing if that's possible. BTW - when putting in code fragments in here, is there a way to indent a whole block. I find that selecting a whole block and then hitting tab does not work.


Solution

  • If you really want to do this, here's a way:

    self.__dict__.update(
        variable1 = 1,
        variable2 = 2,
        variable3 = 'hello')
    

    I'd usually just type self or use copy&paste in my editor.