I recently started using Python 2.6 for Ubuntu Server admin and have two minor issues concerning redundancy:
First thing are imports: They all look something like
import Class from Class
from class import Class
And the second thing are __init__
methods:
__init__(self,arg1,...,argn):
self.arg1 = arg1
...
self.argn = argn
Are there ways to avoid these duplications?
The second thing is not redundancy - it is setting instance attributes. You can do it also like this:
class Foo:
def __init__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
But then you need to call Foo like this:
Foo(arg1=1, arg2=2, arg3=3)
Also your import seems to have improper syntax. It should be from Class import Class
. This looks redundant to you, because it seems, that you are storing each class in a separate file (module) - and that is exactly redundant. Python is not Java, you should usually hold more objects in one module. Keep in mind, that module itself is an object. Also you should name modules properly - the default code style guide says that modules should be all lowercase with no special chars. Like re
or urllib
for example.
from module import Class
It is common for class names to be different from their containing module's name. If you have just one class per module with an identical name, consider moving that class up a level in your hierarchy.
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
This does often seem to be kinda annoying, but it's really not bad, readability-wise, compared to alternatives. However, if you have a lot of parameters that you merely assign as attributes with no other work in your init, then consider inheriting from a namedtuple or similar, which can generate such boilerplate for you. (Namedtuple in particular has other ramifications and will only be sometimes suitable. I'm using it as an example of a base class which can handle this type of boilerplate.)
Version for args:
class Foo:
def __init__(self, *args):
for index,arg in enumerate(args):
setattr(self, 'arg%s'%index, arg)
Foo(1,2,3)
>>> Foo.arg0
1
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