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
Run Code Online (Sandbox Code Playgroud)
不工作......
checkSegment如果输入不是由nucleotids字母组成的字符串,或者如果包含不能在一起的nucleotids,则函数返回1;checkXNA返回带有信息"dnaSegment"或"rnaSegment"的字符串; 工作得很好.但是echo,为打印更具体的信息而设计的功能告诉我,自我没有定义,但为什么呢?
self 在函数定义时没有定义,不能用它来创建默认参数.
函数定义中的表达式在创建函数时进行评估,而不是在调用函数时,请参阅"最小惊讶"和可变默认参数.
请改用以下技术:
def echo(self, start=0, stop=None, search=None):
if stop is None:
stop = len(self.codeSegment)
Run Code Online (Sandbox Code Playgroud)
如果您需要支持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)
Run Code Online (Sandbox Code Playgroud)
在计算函数或方法定义时,即在解析类时,将评估默认参数值.
编写依赖于对象状态的默认参数值的方法是None用作标记:
def echo(self,start=0,stop=None,search=None):
if stop is None:
stop = len(self.codeSegment)
pass
Run Code Online (Sandbox Code Playgroud)