开发者

Python: convenient way to initialize lots of class members

开发者 https://www.devze.com 2023-02-27 07:06 出处:网络
If I have lots of class variables to initialize, any way to shorten the use of \"self.\" ? That is, instead of doing:

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:

开发者_StackOverflow
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.


There are ways to do this, but I wouldn't suggest them. It hampers readability.


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.


Another alternative, just for fun:

myvars = { 'variable1': 1,
           'variable2': 10,
           'variable3': "Hello" }

for name, value in myvars.iteritems():
    setattr(self, name, value)
0

精彩评论

暂无评论...
验证码 换一张
取 消