Python中的attr_reader

时间:2012-04-09 15:46:02

标签: python ruby

python中的attr_reader是否有“同义词”,就像没有让我输入的东西一样?:

class Foo():
    def __init__(self, foo, bar, spam, spammity, spam, spam, quux, foobar, barfoo):
        self.foo = foo
        self.bar = bar
        self.spam = spam
        # And so on...

使self.foo = foo, etc.成为一行,就像红宝石的attr_reader将如何制作

@foo = foo

4 个答案:

答案 0 :(得分:3)

要设置所有内容,请尝试:

class Foo():
  def __init__(self, **kwargs):
    for k,v in kwargs.items():
        setattr(self, k, v)

或者只是一些属性:

class Foo():
  def __init__(self, **kwargs):
    for k in ['foo', 'bar', 'spam']:
        setattr(self, k, kwargs[k])

或者来自(某些)ctor args:

class Foo():
  def __init__(self, foo, bar, spam, bork, kevork):
    for k in ['foo', 'bar']:
        setattr(self, k, locals()[k])

或者所有人:

class Foo():
  def __init__(self, foo, bar, spam, bork, kevork):
    args = dict(locals())
    for k, v in (k,v for k,v in args.items() if not k == 'self'):
        setattr(self, k, v)

答案 1 :(得分:1)

你可以用kwargs做到这一点:

class Foo():
  def __init__(self, **kwargs):
    self.foo = kwargs['foo']

你传递了命名参数:

foo = Foo(foo='bar')

当然,您可能希望捕获KeyError异常

答案 2 :(得分:1)

您可以使用setattr从名为args的关键字设置self attr。

>>> class Foo():
...     def __init__(self, **kwargs):
...         for attr_name in kwargs.keys():
...             setattr(self,attr_name,kwargs[attr_name])
... 
>>> j=Foo(it_works='cool!!')
>>> j.it_works
'cool!!'

答案 3 :(得分:1)

您想要做的事情可以使用locals()完全使用位置参数完成:

class Foo():
   def __init__(self, foo, bar, spam, spammity, spaam, 
                spamm, quux, foobar, barfoo):
       self.__dict__.update(locals())

f = Foo(1, 2, 3, 4, 5, 6, 7, 8, 9)
print f.spamm   # 6

(我更改了arglist中的两个spam,因为Python不喜欢使用多个具有相同名称的参数。)

请注意,所有本地人将成为实例上的属性。如果您想要静态初始化一堆属性,这可能很方便,因为您不需要在它们前面键入self

class Foo():
   def __init__(self, foo, bar, spam, spammity, spaam, 
                spamm, quux, foobar, barfoo):
       a = b = c = 0
       self.__dict__.update(locals())   # sets a, b, and c too

但是,如果您接受关键字参数,则需要从更新中排除该变量,或者之后更可能只是del self.kwargs