Is there a "synonym" for attr_reader
in 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
The attr_reader method takes the names of the object's attributes as arguments and automatically creates getter methods for each.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With