reaching hidden methods + casting

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Apr 12 03:42:30 EDT 2007


En Thu, 12 Apr 2007 04:18:19 -0300, per9000 <per9000 at gmail.com> escribió:

> Hi,
> can I reach a hidden method when doing ugly inheritance in python?
>
>>>> class A:
> ...     def spin(self, n): print "A", n
> ...
>>>> class B:
> ...     def spin(self, m): print "B", m
> ...
>>>> class C(A,B):
> ...     def spin(self, k): print "C", k
> ...
>>>> myC = C()
>>>> dir(myC)
> ['__doc__', '__module__', 'spin']
>
> In f.x. the C-family of languages I guess something like this would
> call B.spin:
> ((B)myC).spin("Lancelot"); // almost forgot the ';'

Try this in Python:
B.spin(myC, "Lancelot")

You can't ask the instance for myC.spin because that would retrieve  
C.spin; you need B.spin instead. But if you get it this way, it's not  
associated to a specific instance, so you must pass myC explicitely  
(becoming 'self').

> Please correct me I am wrong (which I likely am) but as I understand
> it this example calls the constructor of int instead of casting it,
> right?
>>>> leet = int('1337')
>>>> leet
> 1337

Yes.

> So is there another way of digging into the past of a class? Or can/
> should I create constructors for the classes A, B and C that takes
> objects of the other classes?

No need for that. And usually, that's not what you want either: you're  
creating a *different* object that way, not calling a (shadowed) method on  
an existing object.

> Or should I have thought about getting unique names before I
> implemented the ugly inheritance graph?

Perhaps...

-- 
Gabriel Genellina




More information about the Python-list mailing list