Why this fails??
Dave Angel
d at davea.name
Wed Feb 29 05:34:04 EST 2012
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
More information about the Python-list
mailing list