Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In Python 3.x you can simply do what you want:</p> <pre><code>A.print_x(b) #&lt;-- 'eggs' </code></pre> <p>If you only have an instance of 'A', then get the class first:</p> <pre><code>a.__class__.print_x(b) #&lt;-- 'eggs' </code></pre> <p>In Python 2.x (which the OP uses) this doesn't work, as noted by the OP and explained by Amber in the comments: </p> <blockquote> <p><em>This is a difference between Python 2.x and Python 3.x - methods in 3.x don't enforce being passed the same class.</em></p> </blockquote> <h2>More details (OP edit)</h2> <p>In python 2, <code>A.print_x</code> returns an "unbound method", which cannot be directly applied to other classes' objects: </p> <blockquote> <p>When an unbound user-defined method object is called, the underlying function (im_func) is called, with the restriction that the first argument must be an instance of the proper class (im_class) or of a derived class thereof. >> <a href="http://docs.python.org/reference/datamodel.html" rel="noreferrer">http://docs.python.org/reference/datamodel.html</a></p> </blockquote> <p>To work around this restriction, we first have to obtain a "raw" function from a method, via <code>im_func</code> or <code>__func__</code> (2.6+), which then can be called passing an object. This works on both classes and instances:</p> <pre><code># python 2.5- A.print_x.im_func(b) a.print_x.im_func(b) # python 2.6+ A.print_x.__func__(b) a.print_x.__func__(b) </code></pre> <p>In python 3 there's no such thing anymore as unbound method.</p> <blockquote> <p>Unbound methods are gone for good. ClassObject.method returns an ordinary function object, instance.method still returns a bound method object. >> <a href="http://www.python.org/getit/releases/3.0/NEWS.txt" rel="noreferrer">http://www.python.org/getit/releases/3.0/NEWS.txt</a></p> </blockquote> <p>Hence, in python 3, <code>A.print_x</code> is just a function, and can be called right away and <code>a.print_x</code> still has to be unbounded:</p> <pre><code># python 3.0+ A.print_x(b) a.print_x.__func__(b) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload