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:
开发者_StackOverflowwith 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)
精彩评论