Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

Why this fails??

 

 

Python python RSS feed   Index | Next | Previous | View Threaded


ssmile03 at gmail

Feb 29, 2012, 1:07 AM

Post #1 of 2 (153 views)
Permalink
Why this fails??

Why below fails -

----
#!/usr/bin/python

import pickle

class MyClass(object):

Field1 = None
Field2 = None

def __init__(self, dictionary):
self.__dict__.update(dictionary)

my_List = {'Field1': 'Apple', 'Field2': 'Orange'}
myInst = MyClass(my_List)

with open('/tmp/readfile.pkl', 'wb') as f:
pickle.dump(myInst, f)
----

with below error messges -

$ ./pickleClassWrite.py
Traceback (most recent call last):
File "./pickleClassWrite.py", line 5, in <module>
class MyClass(object):
File "./pickleClassWrite.py", line 14, in MyClass
myInst = MyClass(my_List)
NameError: name 'MyClass' is not defined
---


d at davea

Feb 29, 2012, 2:34 AM

Post #2 of 2 (149 views)
Permalink
Re: Why this fails?? [In reply to]

On 02/29/2012 04:07 AM, Smiley 4321 wrote:
> Why below fails -
>
> ----
> #!/usr/bin/python
>
> import pickle
>
> class MyClass(object):
>
> Field1 = None
> Field2 = None
>
> def __init__(self, dictionary):
> self.__dict__.update(dictionary)
>
> my_List = {'Field1': 'Apple', 'Field2': 'Orange'}
> myInst = MyClass(my_List)
>
> with open('/tmp/readfile.pkl', 'wb') as f:
> pickle.dump(myInst, f)
> ----
>
> with below error messges -
>
> $ ./pickleClassWrite.py
> Traceback (most recent call last):
> File "./pickleClassWrite.py", line 5, in<module>
> class MyClass(object):
> File "./pickleClassWrite.py", line 14, in MyClass
> myInst = MyClass(my_List)
> NameError: name 'MyClass' is not defined
> ---
>

The reason for the error is that you're trying to use the class (by
name) before its definition is complete.

The cause is that the code starting with the line "my_list = {Field1...
" should have been dedented to be at top-level. You don't want those
last 4 lines to be inside the class.





--

DaveA

--
http://mail.python.org/mailman/listinfo/python-list

Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact Gossamer Threads
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.