2012-11-07 40 views
3
class makeCode: 
    def __init__(self,code): 
      self.codeSegment = code.upper() 
      if checkSegment(self.codeSegment): 
        quit() 
      self.info=checkXNA(self.codeSegment) 
    def echo(self,start=0,stop=len(self.codeSegment),search=None): #--> self not defined 
      pass 

不工作...Python代码,自定义不

  • 它说,当它实际上是可变没有定义;
  • 函数checkSegment如果输入不是由核苷酸字母组成的字符串,或者包含不能在一起的核苷酸,则返回1;
  • 如果发生这种情况,它会退出,没关系,它可以很好地工作;
  • 然后它分配信息(如果它是RNA或DNA),检查函数checkXNA,返回带有信息“dnaSegment”或“rnaSegment”的字符串;完美的作品。

但是,功能echo将被设计用于打印更具体的信息告诉我,自我没有定义,但为什么?

回答

5

self未在函数定义时定义,您不能使用它来创建默认参数。

函数定义中的表达式在函数创建时评估为,而不是在调用时,请参阅"Least Astonishment" and the Mutable Default Argument

使用以下技术来代替:

def echo(self, start=0, stop=None, search=None): 
    if stop is None: 
     stop = len(self.codeSegment) 

如果您需要支持None作为一个可能的值stop(例如,如果明确指定Nonestop有效值),你需要选择一个不同的唯一前哨使用方法:当函数或方法的定义被评估

_sentinel = object() 

class makeCode: 
    def echo(self, start=0, stop=_sentinel, search=None): 
     if stop is _sentinel: 
      stop = len(self.codeSegment) 
5

默认参数值进行评价时,即,当类被解析。

写依赖于对象状态的默认参数值的方法是使用None列为定点:

def echo(self,start=0,stop=None,search=None): 
    if stop is None: 
     stop = len(self.codeSegment) 
    pass