Search code examples
pythonmethod-parametersclass-attribute

Using class attribute in method definition as argument?


I have the following code :

class Blah:
  ABC, DEF = range(2)

  def meth(self, arg=Blah.ABC):
     .....

Blah.ABC works inside the method or any place outside , the only place it does not work is in the method definition !!!

Any way to resolve this ???


Solution

  • Don't use the class name Blah yet since it hasn't finished being constructed. But you can directly access the class member ABC without prefacing it with the class:

    class Blah:
        ABC, DEF = range(2)
    
        def meth(self, arg=ABC):
            print arg
    
    Blah().meth()
    # it prints '0'
    

    It also works using 'new' style class definition, eg:

    class Blah(object):
        ABC, DEF = range(2)
    

    By the time I really got into python, new style classes were the norm, and they are much more like other OO languages.. so that's all I use. Not sure what the advantages are (if any) to sticking with the old way.. but it seems deprecated, so I would say that unless there's a reason I would use the new style. Perhaps someone else can comment on this.