data attributes override method attributes?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Sep 25 10:12:09 EDT 2012


On Tue, 25 Sep 2012 06:41:43 -0700, Jayden wrote:

> Dear All,
> 
> In the Python Tutorial, Section 9.4, it is said that
> 
> "Data attributes override method attributes with the same name."
> 
> But in my testing as follows:
> 
> #Begin
> class A:
> 	i = 10
> 	def i():
> 		print 'i'
> 
> A.i
>    <unbound method A.i>
> #End
> 
> I think A.i should be the number 10 but it is the method. There must be
> something I misunderstand. Would you please tell me why?

When you create the class, two things happen: first you define a class-
level attribute i, then you define a method i. Since you can only have a 
single object with the same name in the same place, the method replaces 
the attribute.

In this case, classes and methods are irrelevant. It is exactly the same 
behaviour as this:

i = 10
i = 20
# i now equals 20, not 10


except that instead of 20, you use a function object:

i = 10
def i():
    return "something"
# i is now a function object, not 10


What the manual refers to is the use of attributes on an instance:

py> class Test(object):
...     def f(self):
...         return "something"
...
py> t = Test()
py> t.f = 20
py> t.f
20

In this case, there is an attribute called "f" (a method) which lives in 
the class and is shared by all instances, and another attribute called 
"f" which lives in the instance t, is not shared, and has the value 20. 
This instance attribute masks the method with the same name. We can see 
that it is only hidden, not gone, by creating a new instance:

py> u = Test()
py> u.f
<bound method Test.f of <__main__.Test object at 0x871390c>>



-- 
Steven



More information about the Python-list mailing list