basic class question..
Tim Chase
python.list at tim.thechases.com
Sun Nov 15 08:15:28 EST 2009
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
More information about the Python-list
mailing list