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

Not working...

  • it says that the variable self is not defined when it actually was;
  • the function checkSegment returns 1 if the input was not a string made of nucleotids letter, or if that contains nucleotids that can't be together;
  • it quits if that happens, that's ok it works perfectly;
  • then it assigns the information (if it's RNA or DNA) checking with the function checkXNA that returns a string with the information "dnaSegment" or "rnaSegment"; works perfectly.

But then the function echo which will be designed for printing more specific information tells me that self is not defined, but why?

mrk
5,1273 gold badges29 silver badges42 bronze badges
asked Nov 7, 2012 at 15:25
0

2 Answers 2

6

self is not defined at function definition time, you cannot use it to create a default argument.

Expressions in a function definition are evaluated when the function is created, not when it is being called, see "Least Astonishment" and the Mutable Default Argument.

Use the following technique instead:

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

If you need to support None as a possible value for stop (e.g. None is a valid value for stop if specified explicitly), you'll need to pick a different unique sentinel to use:

_sentinel = object()
class makeCode:
 def echo(self, start=0, stop=_sentinel, search=None):
 if stop is _sentinel:
 stop = len(self.codeSegment)
answered Nov 7, 2012 at 15:28
Sign up to request clarification or add additional context in comments.

Comments

6

A default parameter value is evaluated when the function or method definition is evaluated, i.e. when the class is parsed.

The way to write default parameter values that depend on object state is to use None as a sentinel:

def echo(self,start=0,stop=None,search=None):
 if stop is None:
 stop = len(self.codeSegment)
 pass
answered Nov 7, 2012 at 15:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.