On 11월15일, 오후10시15분, Tim Chase <python.l...@tim.thechases.com> wrote: > Pyrot wrote: > > class rawDNA: > > import string > > trans = string.maketrans("GATC","CTAG") > > > def __init__(self, template = "GATTACA"): > > self.template = template //shouldn't this make "template" > > accessible within the scope of "rawDNA"?? > > No. Python's scope resolution consists only of "local, global, > or explicit". There is no "try to find this in the instance or > class" scope-resolution guessing. Your code makes "template" > accessible within the scope of "self", not in a global > unqualified scope. > > So this: > > > def noncoding(self): > > print template.translate(trans) // > > tries to reference "template" first in the local scope (within > noncoding(), but it doesn't exist there), then in the global > scope (it also doesn't exist there), and stops. > > It should be as you have it here: > > > class rawDNA: > > import string > > trans = string.maketrans("GATC","CTAG") > > def __init__(self, template = "GATTACA"): > > self.template = template > > def noncoding(self): > > print self.template.translate(trans) > > Here, you start with "self" which *is* in the local scope, which > *does* contain "template" and so it successfully finds it and all > is [qualifiedly] good. However, you'll also find that "trans" > isn't found because it's neither in the local nor global scope: > > >>> class RawDNA: > ... import string > ... trans = string.maketrans("GATC", "CTAG") > ... def __init__(self, template="GATTACA"): > ... self.template = template > ... def noncoding(self): > ... print self.template.translate(trans) > ... > >>> r = RawDNA() > >>> r.noncoding() > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "<stdin>", line 7, in noncoding > NameError: global name 'trans' is not defined > > so you need to fully qualify it as "RawDNA.trans" for Python to > find it. (I also shifted to using the PEP-8 naming convention > "RawDNA" instead of "rawDNA"). > > Which you indeed discovered: > > > this works as intended. > > Being explicit is part of "Python Zen" (from the python > command-prompt, type "import this" to see the whole list) > > -tkc
thanks! one last question, is "self.template.translate(trans)" the right way to go(pythonic?)? I found it to be cumbersome(and a mouthful) and thought I might have been doing it wrong :-) -- http://mail.python.org/mailman/listinfo/python-list