[Tutor] python instances and type
Andre Engels
andreengels at gmail.com
Mon Apr 16 10:58:49 CEST 2007
2007/4/16, Adam Pridgen <atpridgen at mail.utexas.edu>:
> Hello,
>
> Sorry for the long email, but thanks in advance.
>
> I am not quite sure what is happening, so I have not been able to
> adequately seek a solution via Google, so if this answer is fairly
> easy to find on Google, let me know. I am not sure how to produce an
> example of my problem without using the python code and classes that I
> have, so I will try to compose an effective theoretical example
> below. If there are any clarifications to be made please let me know.
>
> Basically the problem I am having is obtaining the proper type
> identification from a Python object. So going through the motions,
> lets say I have 2 types:
> class foo_1:
> data = ""
> class foo_2:
> foo_1s={}
>
> Time goes by and some assignments are performed and foo_2 is populated
> with some foo_1 objects. Now, I am using the the function below,
> get_class_resolution to get the type of foo_1 and foo_2, and it works
> well when I don't perform any black magic voodoo and simply use after
> the object is created.
>
> It would return the string "foo_1" for the example below:
>
> x = foo_1()
> x.data = "boring"
> print type(x), type(x).mro()
> <class 'foo_1'> [<class 'foo_1'>]
> print get_class_resolution(x)
> foo_1
Would it? When I try it out, I get:
>>> class foo_1:
data = ""
>>> x = foo_1()
>>> x.data = "boring"
>>> print type(x), type(x).mro()
<type 'instance'> [<type 'instance'>, <type 'object'>]
>>> get_class_resolution(x)
[<type 'instance'>, <type 'object'>]
<type 'instance'>
'instance'
To get your desired behaviour, you need something like:
>>> class foo_1(object):
data = ""
>>> x = foo_1()
>>> x.data = "boring"
>>> print type(x), type(x).mro()
<class '__main__.foo_1'> [<class '__main__.foo_1'>, <type 'object'>]
>>> get_class_resolution(x)
[<class '__main__.foo_1'>, <type 'object'>]
<class '__main__.foo_1'>
'__main__'
>>>
--
Andre Engels, andreengels at gmail.com
ICQ: 6260644 -- Skype: a_engels
More information about the Tutor
mailing list