473,662 Members | 2,596 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to use __getattribute_ _ to access a class attribute?

I have the situation where I need to construct the name
of a static method, and then retrieve the corresponding
function from a class object.

I thought I could just use __getattribute_ _ for this purpose.
This works fine if I already have an instantiation of the class,
but not when I try this on the class object directly.

A bare bones example:
class C(object): def a():
print "static method a"
a = staticmethod(a)

It works for a instantiation of class C:
x = C()
x.a <function a at 0x00A981B0> x.__getattribut e__('a') <function a at 0x00A981B0> x.__getattribut e__('a')() static method a

But for the class object it works differently:
C.a <function a at 0x00A981B0> C.__getattribut e__(C,'a') <staticmethod object at 0x00AC6A10> C.a() static method a C.__getattribut e__(C,'a')()
Traceback (most recent call last):
File "<pyshell#219>" , line 1, in -toplevel-
C.__getattribut e__(C,'a')()
TypeError: 'staticmethod' object is not callable

After some experimentation and documentation searching,
I found that to get at the actual function, the __get__
method for the staticmethod descriptor must be called:
C.__getattribut e__(C,'a').__ge t__(None, C) <function a at 0x00A981B0> C.__getattribut e__(C,'a').__ge t__(None, C)() static method a

If I use an class instance as the first argument
it works OK. But I ran into this problem when I tried
to use __getattribute_ _ in the __new__ function of a class
-- there is no class instance yet at that point,
and calling C() there leads to infinite recursion.

Another variant that worked is to call __getattribute_ _
on the metaclass:
type(C).__getat tribute__(C,'a' ) <function a at 0x00A981B0> type(C).__getat tribute__(C,'a' )()

static method a

But according to section 3.3.2.1 of the Language Reference
(More attribute access for new-style classes),
__getattribute_ _ "... should return the (computed) attribute value".
This could be interpreted to say that __getattribute_ _ should
return the function, not the staticmethod object.

Is there a reason for this difference in behavior?

Jul 18 '05 #1
6 3626
Perhaps it might be easier if you made your own static method object:
class MyStaticMethod( object): .... def __call__(self):
.... print "static method a"
.... def __get__(self, cls, inst):
.... return self.__call__
.... class C(object): .... a = MyStaticMethod( ) C.a <bound method MyStaticMethod. __call__ of <__main__.MySta ticMethod object at
0x00E57390>> C.a() static method a C.__getattribut e__(C,'a') <__main__.MySta ticMethod object at 0x00E57390> C.__getattribut e__(C,'a')() static method a c = C()
c.a() static method a C.__getattribut e__(c,'a') <bound method MyStaticMethod. __call__ of <__main__.MySta ticMethod object at
0x00E57390>> C.__getattribut e__(c,'a')()
static method a

As far as your question goes, __getattribute_ _ is following the "... should
return the (computed) attribute value" rule for retrieving the static method
object... unfortunatly the calculated value in this case is a reference to
the static method object rather then the __get__ method bound to the static
method object.

HTH

Chris

"Ruud de Jong" <ru**********@c onsunet.nl> wrote in message
news:40******** **************@ dreader2.news.t iscali.nl...
I have the situation where I need to construct the name
of a static method, and then retrieve the corresponding
function from a class object.

I thought I could just use __getattribute_ _ for this purpose.
This works fine if I already have an instantiation of the class,
but not when I try this on the class object directly.

A bare bones example:
>>> class C(object): def a():
print "static method a"
a = staticmethod(a)

It works for a instantiation of class C:
>>> x = C()
>>> x.a <function a at 0x00A981B0> >>> x.__getattribut e__('a') <function a at 0x00A981B0> >>> x.__getattribut e__('a')() static method a

But for the class object it works differently:
>>> C.a <function a at 0x00A981B0> >>> C.__getattribut e__(C,'a') <staticmethod object at 0x00AC6A10> >>> C.a() static method a >>> C.__getattribut e__(C,'a')()
Traceback (most recent call last):
File "<pyshell#219>" , line 1, in -toplevel-
C.__getattribut e__(C,'a')()
TypeError: 'staticmethod' object is not callable

After some experimentation and documentation searching,
I found that to get at the actual function, the __get__
method for the staticmethod descriptor must be called:
>>> C.__getattribut e__(C,'a').__ge t__(None, C) <function a at 0x00A981B0> >>> C.__getattribut e__(C,'a').__ge t__(None, C)() static method a

If I use an class instance as the first argument
it works OK. But I ran into this problem when I tried
to use __getattribute_ _ in the __new__ function of a class
-- there is no class instance yet at that point,
and calling C() there leads to infinite recursion.

Another variant that worked is to call __getattribute_ _
on the metaclass:
>>> type(C).__getat tribute__(C,'a' ) <function a at 0x00A981B0> >>> type(C).__getat tribute__(C,'a' )()

static method a

But according to section 3.3.2.1 of the Language Reference
(More attribute access for new-style classes),
__getattribute_ _ "... should return the (computed) attribute value".
This could be interpreted to say that __getattribute_ _ should
return the function, not the staticmethod object.

Is there a reason for this difference in behavior?

Jul 18 '05 #2
Ruud de Jong <ru**********@c onsunet.nl> wrote in message news:<40******* *************** @dreader2.news. tiscali.nl>...
Ruud de Jong wrote:
I have the situation where I need to construct the name
of a static method, and then retrieve the corresponding
function from a class object.
If what you're trying to do is get C.a (where C is the class and a is
the name of the staticmethod) but all you have is the class C and a
string mname = "a", then just getattr(C, mname) should work. Generally
this works for any attribute access where you have the attribute name
in another variable.

Another way to get the naked function, which also works for
classmethods, is to do C.__dict__['a']. See comments below that
explain what you see.
I thought I could just use __getattribute_ _ for this purpose.
This works fine if I already have an instantiation of the class,
but not when I try this on the class object directly.

A bare bones example:
>>> class C(object): def a():
print "static method a"
a = staticmethod(a)

It works for a instantiation of class C:
>>> x = C()
>>> x.a <function a at 0x00A981B0> >>> x.__getattribut e__('a') <function a at 0x00A981B0> >>> x.__getattribut e__('a')() static method a
When Python comes across x.a, it doesn't call x.__getattribut e__('a'),
it calls type(x).__getat tribute__(x, 'a'). Now type(x) is C, and it
just so happens (in this case) that x.__getattribut e__ also ends up
calling the same method, since x doesn't have a __getattribute_ _ of
its own. This is why what you do above works.
But for the class object it works differently:
>>> C.a <function a at 0x00A981B0> >>> C.__getattribut e__(C,'a') <staticmethod object at 0x00AC6A10> >>> C.a() static method a >>> C.__getattribut e__(C,'a')()


Traceback (most recent call last):
File "<pyshell#219>" , line 1, in -toplevel-
C.__getattribut e__(C,'a')()
TypeError: 'staticmethod' object is not callable


To repeat the same experiment, you should call
type(C).__getat tribute__(C, 'a'). Note that in this case C *has* its
own __getattribute_ _ attribute (which is meant for instances of C, not
C itself). In fact you do this later, and it works. Hmm, at first
glance I'd expect what you do above to return an exception if passed C
instead of an instance of C (like any other well behaved method). I
don't know why that doesn't happen.

In conclusion, __getattribute_ _() does return the computed attribute
value, but for an object o it is called on type(o) and not o itself.
Also, getattr() is usually all you need.

HTH,
Shalabh
Jul 18 '05 #3
Ruud de Jong wrote:
I have the situation where I need to construct the name
of a static method, and then retrieve the corresponding
function from a class object.
If what you're trying to do is get C.a (where C is the class and a is
the name of the staticmethod) but all you have is the class C and a
string mname = "a", then just getattr(C, mname) should work. Generally
this works for any attribute access where you have the attribute name in
another variable.

Another way to get the naked function, which also works for
classmethods, is to do C.__dict__['a']. See comments below that explain
what you see.
I thought I could just use __getattribute_ _ for this purpose.
This works fine if I already have an instantiation of the class,
but not when I try this on the class object directly.

A bare bones example:
>>> class C(object): def a():
print "static method a"
a = staticmethod(a)

It works for a instantiation of class C:
>>> x = C()
>>> x.a <function a at 0x00A981B0> >>> x.__getattribut e__('a') <function a at 0x00A981B0> >>> x.__getattribut e__('a')() static method a
When Python comes across x.a, it doesn't call x.__getattribut e__('a'),
it calls type(x).__getat tribute__(x, 'a'). Now type(x) is C, and it just
so happens (in this case) that x.__getattribut e__ also ends up calling
the same method, since x doesn't have a __getattribute_ _ of its own.
This is why what you do above works.
But for the class object it works differently:
>>> C.a <function a at 0x00A981B0> >>> C.__getattribut e__(C,'a') <staticmethod object at 0x00AC6A10> >>> C.a() static method a >>> C.__getattribut e__(C,'a')()


Traceback (most recent call last):
File "<pyshell#219>" , line 1, in -toplevel-
C.__getattribut e__(C,'a')()
TypeError: 'staticmethod' object is not callable


To repeat the same experiment, you should call
type(C).__getat tribute__(C, 'a'). Note that in this case C *has* its own
__getattribute_ _ attribute (which is meant for instances of C, not C
itself). In fact you do this later, and it works. Hmm, at first glance
I'd expect what you do above to return an exception if passed C instead
of an instance of C (like any other well behaved method). I don't know
why that doesn't happen.

In conclusion, __getattribute_ _() does return the computed attribute
value, but for an object o it is called on the type(o) and not o itself.
Also, getattr() is usually all you need.

HTH,
Shalabh

Jul 18 '05 #4
Ivo
A good read you can find : www.diveintopython.com

"Ruud de Jong" <ru**********@c onsunet.nl> wrote in message
news:40******** **************@ dreader2.news.t iscali.nl...
I have the situation where I need to construct the name
of a static method, and then retrieve the corresponding
function from a class object.

I thought I could just use __getattribute_ _ for this purpose.
This works fine if I already have an instantiation of the class,
but not when I try this on the class object directly.

A bare bones example:
>>> class C(object): def a():
print "static method a"
a = staticmethod(a)

It works for a instantiation of class C:
>>> x = C()
>>> x.a <function a at 0x00A981B0> >>> x.__getattribut e__('a') <function a at 0x00A981B0> >>> x.__getattribut e__('a')() static method a

But for the class object it works differently:
>>> C.a <function a at 0x00A981B0> >>> C.__getattribut e__(C,'a') <staticmethod object at 0x00AC6A10> >>> C.a() static method a >>> C.__getattribut e__(C,'a')()
Traceback (most recent call last):
File "<pyshell#219>" , line 1, in -toplevel-
C.__getattribut e__(C,'a')()
TypeError: 'staticmethod' object is not callable

After some experimentation and documentation searching,
I found that to get at the actual function, the __get__
method for the staticmethod descriptor must be called:
>>> C.__getattribut e__(C,'a').__ge t__(None, C) <function a at 0x00A981B0> >>> C.__getattribut e__(C,'a').__ge t__(None, C)() static method a

If I use an class instance as the first argument
it works OK. But I ran into this problem when I tried
to use __getattribute_ _ in the __new__ function of a class
-- there is no class instance yet at that point,
and calling C() there leads to infinite recursion.

Another variant that worked is to call __getattribute_ _
on the metaclass:
>>> type(C).__getat tribute__(C,'a' ) <function a at 0x00A981B0> >>> type(C).__getat tribute__(C,'a' )()

static method a

But according to section 3.3.2.1 of the Language Reference
(More attribute access for new-style classes),
__getattribute_ _ "... should return the (computed) attribute value".
This could be interpreted to say that __getattribute_ _ should
return the function, not the staticmethod object.

Is there a reason for this difference in behavior?

Jul 18 '05 #5
Shalabh Chaturvedi schreef:
Ruud de Jong wrote:
I have the situation where I need to construct the name
of a static method, and then retrieve the corresponding
function from a class object.

If what you're trying to do is get C.a (where C is the class and a is
the name of the staticmethod) but all you have is the class C and a
string mname = "a", then just getattr(C, mname) should work. Generally
this works for any attribute access where you have the attribute name in
another variable.


Erh, hmm, rrriight... Built-in functions. <blush/>
Completely forgot about that one -- too focussed
on trying to do everything with object methods and such.
I really need to pay more attention to those built-in functions.

Well, that solves my immediate problem.
I knew there had to be a simple solution :-)

Another way to get the naked function, which also works for
classmethods, is to do C.__dict__['a']. See comments below that explain
what you see.
Well, that's not true, at least not on my system (XP, Python 2.3.3):
class C(object): def a():
print "static method a"
a = staticmethod(a)

C.__dict__['a']

<staticmethod object at 0x00AADD10>
[snipped] To repeat the same experiment, you should call
type(C).__getat tribute__(C, 'a'). Note that in this case C *has* its own
__getattribute_ _ attribute (which is meant for instances of C, not C
itself).
C did not have its own __getattribute_ _ method. It inherited it
from object.

I still find this whole thing slightly ambiguous.
A class C is itself an object, an instance of 'type',
just as x = C() leads to x being an instance of class C.
But x.__getattribut e__ and C.__getattribut e__ return
different objects.
In fact you do this later, and it works. Hmm, at first glance
I'd expect what you do above to return an exception if passed C instead
of an instance of C (like any other well behaved method). I don't know
why that doesn't happen.


I would also have expected an exception. The strange thing, as I see
it, is that x.__getattribut e__ and type(C).__getat tribute__ both give
the correct result, but that C.__getattribut e__ *almost* gives the
correct result, but stops at calling the __get__ function on the
desciptor object.

Anyway, now that you've kindly reminded me of the existance of getattr,
I'll not spend any more time trying to understand this.

Thanks,

Ruud

Jul 18 '05 #6
Ruud de Jong wrote:
Shalabh Chaturvedi schreef:
Ruud de Jong wrote:
I have the situation where I need to construct the name
of a static method, and then retrieve the corresponding
function from a class object.
If what you're trying to do is get C.a (where C is the class and a is
the name of the staticmethod) but all you have is the class C and a
string mname = "a", then just getattr(C, mname) should work. Generally
this works for any attribute access where you have the attribute name
in another variable.

Erh, hmm, rrriight... Built-in functions. <blush/>
Completely forgot about that one -- too focussed
on trying to do everything with object methods and such.
I really need to pay more attention to those built-in functions.

Well, that solves my immediate problem.
I knew there had to be a simple solution :-)

Another way to get the naked function, which also works for
classmethods, is to do C.__dict__['a']. See comments below that
explain what you see.

Well, that's not true, at least not on my system (XP, Python 2.3.3):
>>> class C(object): def a():
print "static method a"
a = staticmethod(a)

>>> C.__dict__['a'] <staticmethod object at 0x00AADD10>
> [snipped]


Sorry, my mistake. In fact it doesn't work for even classmethods. Only
for functions.
To repeat the same experiment, you should call
type(C).__getat tribute__(C, 'a'). Note that in this case C *has* its
own __getattribute_ _ attribute (which is meant for instances of C, not
C itself).

C did not have its own __getattribute_ _ method. It inherited it
from object.


True. Left out a little bit of information there (for brevity).
I still find this whole thing slightly ambiguous.
A class C is itself an object, an instance of 'type',
just as x = C() leads to x being an instance of class C.
But x.__getattribut e__ and C.__getattribut e__ return
different objects.
Only if you didn't first do x.__getattribut e___ = None <wink>. then
x.__getattribut e__ doesn't even return anything. x.__getattribut e__ is
never meant to be called. It is only called on /type/ objects. If you
want to get an attribute on obj, you call __getattribute_ _ on type(obj).
(Well that's what Python does, you can just use getattr(obj, 'attr')).
In fact you do this later, and it works. Hmm, at first glance I'd
expect what you do above to return an exception if passed C instead of
an instance of C (like any other well behaved method). I don't know
why that doesn't happen.

I would also have expected an exception. The strange thing, as I see
it, is that x.__getattribut e__ and type(C).__getat tribute__ both give
the correct result, but that C.__getattribut e__ *almost* gives the
correct result, but stops at calling the __get__ function on the
desciptor object.


What C.__getattribut e__ doesn't do (maybe it should?) is to check that
the first argument is an instance of C, or at least an instance of
object. I'm just guessing here, but if it continues with the default
mechanism of __getattribute_ _, it is going to get the staticmethod object.

Anyway, now that you've kindly reminded me of the existance of getattr,
I'll not spend any more time trying to understand this.

Thanks,

Ruud


Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1407
by: Henry 'Pi' James | last post by:
I'm pretty sure this must not be a new idea, but it seems no one else has voiced their agitation about the name "__getattribute__" so far. Its closeness to "__getattr__" is only one thing that irritates tons of people, as is apparent through the endless repeating question about the difference between the two, and through the fact that every lecture on "new classes" in Python feels contrained to explain that difference. More importantly,...
0
6587
by: Gigi | last post by:
Hi, In the Python documentation regarding __getattribute__ (more attribute access for new style classes) it is mentioned that if __getattribute__ is defined __getattr__ will never be called (unless called explicitely). Here is the exact citation: """ The following methods only apply to new-style classes. __getattribute__( self, name)
3
2571
by: Sylvain Ferriol | last post by:
hello when i define __getattribute__ in a class, it is for the class instances but if i want to have a __getattribute__ for class attributes how can i do that ? sylvain
5
2048
by: Stefan Sonnenberg-Carstens | last post by:
Hi there, I'm facing some strange things - but maybe only me is strange - anyway... i wrote the following code: +++ class T(object): def __init__(self,name='',port=80): self.name=name
1
2708
by: pascal.parent | last post by:
Hi, I try to define a (new-style) class who: - have a __slots__ defined to be strict attributes, - return None if the attribute is 'ok' but not set, or raise a 'normal' error if the attribute isn't in __slots__. This code runs, but is it the good way? Thanks.
5
2515
by: Barry Kelly | last post by:
I'm running this version of Python: Python 2.4.3 (#1, May 18 2006, 07:40:45) on cygwin I read in the documentation that these two expressions are interchangeable: x.__getattribute__('name') <==> x.name
4
3308
by: Pedro Werneck | last post by:
Hi all I noticed something strange here while explaining decorators to someone. Not any real use code, but I think it's worth mentioning. When I access a class attribute, on a class with a custom metaclass with a __getattribute__ method, the method is used when acessing some attribute directly with the class object, but not when you do it from the instance.
6
3547
by: Adam Donahue | last post by:
As an exercise I'm attempting to write a metaclass that causes an exception to be thrown whenever a user tries to access 'attributes' (in the traditional sense) via a direct reference. Consider: class X( object ): y = 'private value' def get_y( self ): return self.y
8
1766
by: bukzor | last post by:
I want to make a MixIn class that waits to initialize its super- classes until an attribute of the object is accessed. Not generally useful, but desirable in my case. I've written this, and it works, but would like to take any suggestions you guys have. I've commented out the "delattr" call because it throws an AttributeError (although I don't know why). class LateInitMixIn(object):
0
8435
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8768
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8547
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7368
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5655
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4181
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2763
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1999
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1754
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.