NameError question - def(self, master) - master not in namespace within class?

bieffe62 at gmail.com bieffe62 at gmail.com
Thu Oct 9 11:54:10 EDT 2008


On 9 Ott, 17:43, harijay <hari... at gmail.com> wrote:
> Hi I am new to writing module and object oriented python code. I am
> trying to understand namespaces and classes in python.
>
> I have the following test case given in three files runner , master
> and child. I am getting an error within child where in one line it
> understands variable master.name and in the next line it gives a
> NameError as given here
>
> "    print "Reset name now from %s to %s , oldname %s is saved in
> mastertrash" % (master.trash, master.name , master.trash)
> NameError: name 'master' is not defined"
>
> Sorry for a long post because I dont know how to  frame my question.
> I am pasting the code contained in the three files and the error
> message here
> Thanks for your help
> harijay
>
> The detailed error I get is
> hazel:tmp hari$ python runner.py
> Traceback (most recent call last):
>   File "runner.py", line 3, in <module>
>     import child
>   File "/Users/hari/rpc-ccp4/tmp/child.py", line 1, in <module>
>     class child():
>   File "/Users/hari/rpc-ccp4/tmp/child.py", line 9, in child
>     print "Reset name now from %s to %s , oldname %s is saved in
> mastertrash" % (master.trash, master.name , master.trash)
> NameError: name 'master' is not defined
>
> #File runner.py
> #!/usr/bin/python
> import master
> import child
>
> if __name__=="__main__":
>         print "RUNNING RUNNER"
>         m = master.master("hj","oldhj")
>         s = child.child(m)
>         print "Now I have the variable master name %s and master.trash %s" %
> (m.name , m.trash)
>
> #File master.py
> class master():
>         name=""
>         trash=""
>
>         def __init__(self,name,trash):
>                 self.name = name
>                 self.trash = trash
>
> #File child.py
> class child():
>         def __init__(self,master):
>                 print "Master  name is %s" % master.name
>                 print  "Now seeting master name to setnameinchild in child.py "
>                 tmp = master.trash
>                 master.trash = master.name
>                 master.name = "setnameinchild"
>         print "Reset name now from %s to %s , oldname %s is saved in
> mastertrash" % (master.trash, master.name , master.trash)


You need to have an import master in child.py too.

Ciao
-----
FB

Ciao
----
FB



More information about the Python-list mailing list