confused about the different built-in functions in Python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon May 26 21:21:36 EDT 2014


On Mon, 26 May 2014 23:58:37 +0300, Marko Rauhamaa wrote:

> Marko Rauhamaa <marko at pacujo.net>:
> 
>> Christian Heimes <christian at python.org>:
>>
>>> Python creates a new bound method object every time. A bound method
>>> object is a callable object that keeps a strong reference to the
>>> function, class and object. The bound method object adds the object as
>>> first argument to the function (aka 'self').
>>
>> I stand corrected. I had thought the trampoline ("bound method object")
>> was created once and for all.
> 
> Sure enough. The principle is explicitly specified in <URL:
> https://docs.python.org/3.2/reference/datamodel.html#index-46>.
> 
> Thus:
> 
>    >>> class X:
>    ...   def f(self):
>    ...     print("Hello")
>    ...
>    >>> x = X()
>    >>> x.f()
>    Hello
>    >>> def f(): print("Meh")
>    ...
>    >>> x.f = f
>    >>> x.f()
>    Meh
>    >>> delattr(x, "f")
>    >>> x.f()
>    Hello
> 
> IOW, you can override a method with setattr() but you cannot delete a
> method with delattr().

Of course you can. You just need to know where methods are found. Hint: 
we write this:

class Example:
    def method(self): ...


not this:

class Example:
    def __init__(self):
        def method(self): ...
        self.method = method


Methods are attributes of the class, not the instance. Like all class 
attributes, you can retrieve them by doing a lookup on the instance, you 
can shadow them by storing an attribute of the same name on the instance, 
but you cannot rebind or delete them directly on the instance, since they 
aren't on the instance.



-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list