1

我有以下代码:

class Blah:
  ABC, DEF = range(2)

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

Blah.ABC 在方法内部或外部的任何地方都有效,唯一不起作用的地方是方法定义中!

有什么办法解决这个???

4

1 回答 1

3

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.

于 2016-05-10T00:34:02.137 回答