python - Set instance variable as default parameter to class function -


i have class function takes 4 arguments, class member variables in practice. 1 of these arguments modified @ time , rest of time would-be defaults (current values of class member variables) passed function/written out though aren't changing.

i thought best make these class member variables defaults, i'm having hard time getting best syntax. following code produces behavior desire - using class member variable default parameter function. it's ugly:

class test:     def __init__(self, a, b):         self.a =         self.b = b      def testfunc(self, param = none):         if not param:             param = self.a         print(param)   if __name__ == '__main__':     a1 = test(1, 3)     a1.testfunc()     a2 = test(5, 5)     a2.testfunc()    #(prints 1 , 5 when called) 

i use following:

    def testfunc(self, param = self.a):         print(param) 

but gives error:

nameerror: name 'self' not defined 

what's better way this?

your first attempt pythonic, thing change test:

 def testfunc(self, param = none):         if param none:             param = self.a         print(param) 

the problem testing false 0 , empty container (including empty string) resolve false.

if have large number of these, see understanding kwargs in python


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -