Instance attributes vs method arguments

bieffe62 at gmail.com bieffe62 at gmail.com
Tue Nov 25 09:32:09 CET 2008


On 25 Nov, 08:27, John O'Hagan <resea... at johnohagan.com> wrote:
> Is it better to do this:
>
> class Class_a():
>         def __init__(self, args):
>                 self.a = args.a        
>                 self.b = args.b
>                 self.c = args.c
>                 self.d = args.d
>         def method_ab(self):
>                 return self.a + self.b
>         def method_cd(self):            
>                 return self.c + self.d
>
> or this:
>
> class Class_b():
>         def method_ab(self, args):
>                 a = args.a
>                 b = args.b
>                 return a + b
>         def method_cd(self, args)      
>                 c = args.c
>                 d = args.d
>                 return c + d
>
> ?
>
> Assuming we don't need access to the args from outside the class,
> is there anything to be gained (or lost) by not initialising attributes that
> won't be used unless particular methods are called?
>
> Thanks,
>
> John O'Hagan

If 'args' is an object of some class which has the attribute a,b,c,d,
why don't you just add
method_ab and method_cd to the same class, either directly or by
sibclassing it?

If for some reason you can't do the above, just make two functions:

def function_ab(args): return args.a + args.b
def function_cd(args): return args.c + args.d

One good thing of Python is that you don't have to make classes if you
don't need to ...

Ciao
------
FB



More information about the Python-list mailing list