保留上下文的细节以及我为什么关心......
可以这样做吗:
class IsThisOk(object):
def __init__( self, **kwargs ):
for k in kwargs:
setattr( self, k, kwargs[k] )
obj = IsThisOk( apples=2 , oranges=2 )
因为我一直把它当作:
class OptionB(object):
apples = None
oranges = None
"""class defaults"""
def __init__( self, **kwargs ):
for k in kwargs:
setattr(self,k,kwargs[k])
b = OptionB( apples=2 , oranges=2 )
=====
编辑 :
我最初在上面有这个,这是我不应该有的......
class OptionA(object):
"""set self.k but with class defaults"""
apples = None
oranges = None
def __init__( self, **kwargs ):
for k in kwargs:
self.k = kwargs[k]
a = OptionA( apples=2 , oranges=2 )
这一切都来自我试图优化一些代码。
我还注意到:
for k in kwargs:
setattr( self, k, kwargs[k] )
比
for k,v in kwargs.iteritems():
setattr( self, k, v )