4
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

不工作...

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

但是echo,为打印更具体的信息而设计的功能告诉我 self 没有定义,但为什么呢?

4

2 回答 2

6

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

函数定义中的表达式在创建函数进行评估,而不是在调用它时,请参阅“Least Astonishment”和 Mutable Default Argument

请改用以下技术:

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

如果您需要支持None作为可能的值stop(例如,如果明确指定,则为None有效值stop),您需要选择一个不同的唯一哨兵来使用:

_sentinel = object()

class makeCode:
    def echo(self, start=0, stop=_sentinel, search=None):
        if stop is _sentinel:
            stop = len(self.codeSegment)
于 2012-11-07T15:28:04.937 回答
6

评估函数或方法定义时,即解析类时,评估默认参数值。

编写依赖于对象状态的默认参数值的方法是None用作哨兵:

def echo(self,start=0,stop=None,search=None):
    if stop is None:
        stop = len(self.codeSegment)
    pass
于 2012-11-07T15:29:33.430 回答