简体   繁体   中英

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 ???

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM