Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attr_reader in Python

Tags:

python

ruby

Is there a "synonym" for attr_readerin python, like something that doesn't have to make me type out?:

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...

Just a one line thing that makes self.foo = foo, etc., sort of like how ruby's attr_reader would make

@foo = foo
like image 730
Billjk Avatar asked Apr 09 '12 15:04

Billjk


People also ask

What is Attr_reader?

The attr_reader method takes the names of the object's attributes as arguments and automatically creates getter methods for each.

What is Attr_accessor in Ruby?

attr_accessor is a shortcut method when you need both attr_reader and attr_writer . Since both reading and writing data are common, the idiomatic method attr_accessor is quite useful.


2 Answers

To set everything, try:

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

Or just some attributes:

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

Or from (some) ctor args:

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

Or all of them:

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)
like image 125
Macke Avatar answered Sep 22 '22 12:09

Macke


You can do this with kwargs:

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

And you pass in named arguments:

foo = Foo(foo='bar')

Of course, you might want to catch KeyError exception

like image 25
Intra Avatar answered Sep 20 '22 12:09

Intra