Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #76781
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: when the method __get__ will be called? |
| Date | 2014-08-22 09:27 +0200 |
| Organization | None |
| References | <53F6EC69.6060609@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.13279.1408692437.18130.python-list@python.org> (permalink) |
luofeiyu wrote:
> class C(object):
> a = 'abc'
> def __getattribute__(self, *args, **kwargs):
> print("__getattribute__() is called")
> return object.__getattribute__(self, *args, **kwargs)
> def __getattr__(self, name):
> print("__getattr__() is called ")
> return name + " from getattr"
> def __get__(self, instance, owner):
> print("__get__() is called", instance, owner)
> return self
> def foo(self, x):
> print(x)
>
>
> >>> x=C()
> >>> x.a
> __getattribute__() is called
> 'abc'
> >>> x.b
> __getattribute__() is called
> __getattr__() is called
> 'b from getattr'
>
>
>
>
> If call an attribute which does exist ,__getattribute__() is called
> If call an attribute which does not exist ,__getattribute__() is called
> and then __getattr__() is called ?
You typically use either __getattribute__() which is called for every
attribute or __getattr__() which is called only as a fallback when an
attribute is not found in the instance __dict__.
> when the __get__ method will be called?no chance for my example?
__get__() is part of the descriptor protocol; it is called on attribute
access:
>>> class A(object):
... c = C()
...
>>> A().c
('__get__() is called', <__main__.A object at 0x7f7cc2c8e850>, <class
'__main__.A'>)
<__main__.C object at 0x7f7cc2c8e910>
>>> A.c
('__get__() is called', None, <class '__main__.A'>)
<__main__.C object at 0x7f7cc2c8e910>
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: when the method __get__ will be called? Peter Otten <__peter__@web.de> - 2014-08-22 09:27 +0200
csiph-web