Python Attributes and Methods


Explains the mechanics of attribute access for new-style Python objects:

  • how functions become methods
  • how descriptors and properties work
  • method resolution order for classes

Read The Book


This book is part of a series:

  1. Python Types and Objects

  2. Python Attributes and Methods [you are here]


01 Jun, 2005
Kevin Whitefoot:

Brilliant. Thank you very much for the clearest exposition of Python's type system I have seen.

23 Jul, 2005
Jeronimo Albi:

Yes, very well explained. It's a plesure to read articles like this one. By the way, I really like cafepy site design =).

06 Sep, 2005
Don Bora:

How does one start a new discussion ? I want to start a discuss between PHP and Python , which is better ?

06 Sep, 2005
Don Bora:

Okay i figured it out. Must be tired tonight. :(

17 Jan, 2006

Is there a large python discussion board / community out there somewhere?

18 Jan, 2006

22 Feb, 2006

This is excellent.

I got particularly intersted at SpecialType. It would be interstesting to have the distinction between 'type(list)' ('list' is given in the library doc as a builtin function) and types.ListType made clear.

It seems that 'list' is, in fact, a class or type name and, when called becomes an instance constructor.

Colin W.

22 Feb, 2006
Shalabh Chaturvedi:

Any 'class or type name' when called returns the instance - in fact that is the standard way of creating an instance in Python - call the class name. This is true for built-in types as well as classes you define. The built-in list used to be a function but version 2.2 onward it is a type. Interestingly the behavior seems same as before when you use it to convert something to a list. But technically you are instantiating a list object rather than calling a function.

Also, list and types.ListType are one and the same object. In fact you can check in Python yourself::

import types types.ListType is list True

When you say type(list), you get the metaclass <type 'type'>. See (Python Objects Map), which shows both list (shown as <type 'list'>) and <type 'type'>.

08 Dec, 2006

Thank you very much for these guides. They've answered virtually all of my questions regarding objects and types the standard documentation didn't answer - and there were a lot of those.

06 Oct, 2007

You've written that when retrieving an attribute from an object (print objectname.attrname) the first step performed by Python is to check whether attrname is a Python-provided attribute for objectname and if it is - return it. How exactly is this step performed? Also, I've looked for a good guide explaining what is found in object and what the dictproxy object is, and have found nothing - could you refer me to such a guide?

Thanks in advance!

19 Jan, 2010
V. Argenta*:

Excellent reading about python specificities! I just would say that chapter 2 could be a little more detaild; I had some difficulty reading it. But nothing very serious - all your material is very readable, and you certainly helped me alot. Thanks!

19 Aug, 2010

I think there is an error (or maybe something changed?): in example 1.4, you say:

cobj.dict['d'] = "try to force a value" # Forcing value x = cobj.d # Futile: get is called instead

but some line above you say that resolution order proceed first with instance cobj.dict, then in the type cobj.class.dict

But overriding the class value ( d = Desc() ) with an instance value ( d = [HTML_REMOVED] ) the evaluation order changes. So the x = cobj.d will return the string.

I just tried this with Python 2.6.4:

>>> class Desc(object):
...   def __get__(self, obj, cls=None):
...     return "Desc Get"
>>> class O(object):
...   de = Desc()
>>> o = O()
'Desc Get' # As expected
>>> o.__dict__['de'] = "A string"
'A string' # Resolution order changes

Probably everyone noted this, but was just a fix.

Good article anyway, I love to read about the internals :)


19 Aug, 2010

Ooops, sorry, forgot about _ set _ . My last comment is wrong, sorry again. ~Aki

20 Apr, 2011
Alicante Airport*:

Your insight view is usefule for me. Thanks!

18 Oct, 2011

In the "who's next class" section, Both B, C are super classes of D, but in the implementation of the do_your_stuff() and find_next_class method D will only invoke either B or C's do_your_stuff not both. Is it just for illustration purpose

12 Jan, 2012

Example 1.7 currently does not work as the hidden variable called b does not exist for a first get. To fix it, you need to set b inside init as in

Otherwise, the first get fails. Also, setting seems to just set, and therefore, delete the descriptor from the instance.

Thank you.

21 Jan, 2012

Could you rephrase this part :

«Check objectname.dict for attrname, and return if found. If objectname is a class, search its bases too. If it is a class and a descriptor exists in it or its bases, return the descriptor result.»

The way I understand it is that:

getattirubte looks in object.dict and returns whatever it finds there. If it did not find something it looks inside class bases for a descriptor and returns?

I'm not sure whether getattribute looks for a non-datadescriptor inside the dict of bases or it's looking for a descriptor...


08 Jan, 2013

I'm a college student working on a Python interpreter project, and the section on descriptors ("The Dynamic __dict__") saved my life! I couldn't find this level of detail anywhere in the documentation. Thank you so much for providing this.

There are a couple of points I have noticed by experimentation (with Python 3.2) that you might want to clarify:

  1. A descriptor with either __set__ or __delete__ is considered a data descriptor, and can cause an error if the other one is missing. For example:

    >>> class D:
    ...     def __get__(self, obj, cls=None): pass
    ...     def __set__(self, obj, val): pass
    >>> class C:
    ...     d = D()
    >>> del C().d
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: __delete__
  2. When looking up an attribute, if a non-data descriptor or a non-descriptor is found before a data descriptor in an object's class, it hides any attributes in superclasses. For instance:

    >>> class DD:
    ...     def __get__(self, obj, cls=None):
    ...             print("DD.__get__")
    ...     def __set__(self, obj, val):
    ...             print("DD.__set__")
    ...     def __delete__(self, obj):
    ...             print("DD.__delete__")
    >>> class ND:
    ...     def __get__(self, obj, cls=None):
    ...             print("ND.__get__")
    >>> class C:
    ...     x = DD()
    >>> class D(C):
    ...     x = ND()
    >>> D().x
  3. Python-provided attributes have descriptors too (although I'm not sure if the implementation actually uses them). These are the slot wrappers and such in object, type, etc. Also, a user-defined class can override a Python-provided attribute. For example:

    >>> class C:
    ...     __dict__ = "__dict__"
    >>> c = C()
    >>> c.__dict__
19 Sep, 2013

Excellent. The following sentence from the python documentation led me to your book: 'Data and non-data descriptors differ in how overrides are calculated with respect to entries in an instance’s dictionary.' Your book explained this in crystal clear language, plus a lot more! Great work.

25 Jun, 2014

In example 1.4, PROBLEM: The statement x = cobj.d assigns None to x, yet the narrative reads "Calls d.get(cobj, C). The value returned is bound to x."

Further weirdness:

d.get(cobj, C) Traceback (most recent call last): File "[HTML_REMOVED]", line 1, in [HTML_REMOVED] NameError: name 'd' is not defined

QUESTION: What am I doing wrong / why does it not work?

FOR REFERENCE Examples 1.3, 1.4 class Desc(object): '''A class that can be instantiated to create a descriptor.''' def get(self, obj, cls= None): pass

def __set__(self, obj, val):

def __delete__(self, obj):

class C(object): "A class with a single descriptor" d = Desc() # [1]

cobj = C()

x = cobj.d # [2] cobj.d = "setting a value" # [3] cobj.dict['d'] = "try to force a value" # [4] x = cobj.d # [5] del cobj.d # [6]

x = C.d # [7] C.d = "setting a value on class" # [8]

''' [1] Now the attribute called d is a descriptor.''' ''' [2] Calls d.get(cobj, C). The value returned is bound to x. Here d means the instance of Desc defined in [1]. It can be found in C.dict['d'].''' ''' [3] Calls d.set(cobj, "setting a value").''' ''' [4] Sticking a value directly in the instance's dict works, but...''' ''' [5] is futile. This still calls d.get(cobj, C).''' ''' [6] Calls d.delete(cobj).''' ''' [7] Calls d.get(None, C).''' ''' [8]Doesn't call anything. This replaces the descriptor with a new string object. After this, accessing cobj.d or C.d will just return the string "setting a value on class". The descriptor has been kicked out of C's dict.'''

27 Apr, 2015
guangtjl :

[HTML_REMOVED][HTML_REMOVED]isabel marant[HTML_REMOVED][HTML_REMOVED]You accompanied us all from dawn to dusk, the next two years, you will see we grow, you like a candle, I feel the future is bright, but eventually burn themselves, this is your greatness, your selfless. I loved the exchange of teachers, I prefer be able to prciser I am not a teacher, so I can know what their shortcomings. Can be corrected quickly, as I suppose Minister dorm at school, I have never had any contact, I do not know how, step by step just to explore, Manire exercise their own, I really like communication with the teacher, but I do not dare to know, I do not know what to say, I comptences lack of language, the teacher is in the dark, when I bring my light, the teacher said every word may be infected with me Encouraged me.[HTML_REMOVED][HTML_REMOVED]

[HTML_REMOVED][HTML_REMOVED]tiffany[HTML_REMOVED][HTML_REMOVED]Can you tell me? My horses when we can come? When can russir? Difficult belong right away from me? Today is the first day of military training, and we all put on uniforms ah! Simply gnial. Several people in our class aligns teams, the curious mood rcration in the yard. Our collection of first year on the playing field. Opening ceremony begins! After you cost the speech of Professor Yang, I know the crowd vtue a white dress that will teach us this military officer. Our instructors teach is a working sense of direction humor. Seriously. Afternoon began his military training, the instructors told us to arrter Junzi first foot to form 60 & deg;, the abdomen and chest, looked up, be of eyes with a kind of meurtrire.[HTML_REMOVED][HTML_REMOVED]

[HTML_REMOVED][HTML_REMOVED]prada[HTML_REMOVED][HTML_REMOVED]Rconfortant mother smile, said: ah This is our family tradition. Our family home prs the little walk in the park, has encountered a beggar begging, I originally wanted to go, but I take my mother told me to deceive. My mother said: This is a lie ah. Mum given me some time to change, she said: They could be ah really need help, if each of us considrent as liars, they would not be alive without ns? If this was you, you will also need someone to give you money, right? Go give money to him. After returning home my mother told me ah This is our family tradition. A neighbor very naughty children come to me to play carelessly pre thou up a little goldfish, I thought Oh, miserable, and this little goldfish is prefers to my father ah, have taken care of every day, even to Bb.[HTML_REMOVED][HTML_REMOVED]

[HTML_REMOVED][HTML_REMOVED]pandora[HTML_REMOVED][HTML_REMOVED]It marks the end of the old lunar year. The new year began. People will say goodbye to cold and dull winter respond to the vitality of spring. Feast of Spring, formerly known as the New Year's Day, Sui Qing Du station within five candle book ", said: the first month of the end of the month, Mongol day, Yiyun movement Yiyun Yuanshuo L. intention yuan the head, after that the idea was to start, because that day is the first day of the year, the first day of spring, the first day of the first month, supposedly three yuan, because today is the age of the DPRK, the DPRK month, day of the Core North, called dynasties, and because it is the first Hatsumi, called Yuanshuo. Song Wuzi Mu in "Dream beam recorded, has explained: Hatsumi month that the day of the New Year.[HTML_REMOVED][HTML_REMOVED]

[HTML_REMOVED][HTML_REMOVED]versace[HTML_REMOVED][HTML_REMOVED]Finally, the big dog in front of a pre rcupre not heroic, they bark a few times and fled. At this time, I felt Dad was so great, the father of ct is so sr, the heart is so hot. Daddy is not only courageous, and search. After my primary school, my father is very proccup through learning. For me laborer a detailed plan of the study, buy a variety of different materials learning difficulties. Whenever I encountered problems with homework, Dad would I explain the sudden DIFFERENT Chin. I arrived not only understand, but also let my memory was in prison. In order to improve the mastery of language The Bahamas, Dad often acts as a foreigner, to accompany me to practice for a while. Dad used to tell me: people can not have bad habits, but not without a good hobby.[HTML_REMOVED][HTML_REMOVED]

[HTML_REMOVED][HTML_REMOVED]coach[HTML_REMOVED][HTML_REMOVED]She likes to play? I do not know. Ms. she did not know what she was late age are friends qualifications Nan Yuan? All day, just know that you want to protect, never asked what she likes, birthdays are a few figures. Flax, raw began questioning salptre, they can only relations between the two bystanders and passersby, just look at each other more than just thought that, she to a tear, quickly dtourna to wipe the tears, prcipita out . Lin Lin Yuan Nan salptre Gross Gross poorly understood salptre call his voice, that fragile voice, as if long touchrent fingers, it will disappear. Heard these words, I am salptre crude run faster, it can not comparatre before the Yuan Nan never thought their friendship them might even be so fragile Confucius said: & lsquo; & Rsquo; three lines must be my teacher.[HTML_REMOVED][HTML_REMOVED]

[HTML_REMOVED][HTML_REMOVED]adidas[HTML_REMOVED][HTML_REMOVED]Ceci est un petit fourmis cder la place la belle musique alors qu'ils laisser aller au sommeil. Soudain, un chat gant venu. Ils ont non seulement chou s'chapper, mais aussi pour tout le monde de jouer ensemble. Chats coute de cette berceuse drive aussi le sommeil. Mon frre et je pense que la musique est mieux que tous les vers de la musique du monde. Que oui, la musique cessa, tout ici tait endormi. Mon frre et moi sommes retourns la maison, mon cur est toujours penser ce morceau de musique. L'amour comme un phare pour clairer notre voie suivre; un parapluie dans la prise en charge de la pluie pour d'autres abris, aimer comme une piscine dans les sources du dsert, le cur humain humide, l'amour comme la tasse de th de l'hiver, de donner aux gens chaud.[HTML_REMOVED][HTML_REMOVED]

[HTML_REMOVED][HTML_REMOVED]boss[HTML_REMOVED][HTML_REMOVED]Originally, when we began to rebound, the excitement does not, can be found in the fawn increasingly difficult to go rear and take nearly 40 minutes not yet arrived, but poor long campaign I naturally become sweet tomatoes, hearts balloons also apathetic half, repeatedly to exit the drumbeat. Children work hard, persist. Mom and Dad Encouraged have to say. Oh, good. Ae! Brother does not Drange me to walk on the moss has fallen on the road, unfortunately also sitting on a stone, ass perc, can not help but cry, my brother almost crying, but after my comfort, my brother's face there was a smile. After all roses, we finally saw the yellow fruit falls! There are several miles of the waterfall, we heard the thunder Vals and saw the mist rising hard, got closer, I saw a flood down under exposure to sunlight, such as vacant colored ribbons, beads, flowers clater .[HTML_REMOVED][HTML_REMOVED]

[HTML_REMOVED][HTML_REMOVED]nike air max[HTML_REMOVED][HTML_REMOVED]This fawn, or fortunately not examine non-stop busy all day, o take into account the existence of the invisible in the middle of all the spirits? I put the heavy luggage, walked through, felt walking in the margins Qui remembers who remember exactly who said that my love eternal sentence prcdente is our first campus after injuries that often can hear the song, so we have that some of the memories. Honey, come when my third wife now! Have you done a. I thought my wife? Want a girl his wife to do? Then I just smiled and said: When the first I'd be delighted. Seems rflchir a moment, they use the same for everyone laugh cheap to me: No, you're my real great lady love. See, I do not rpondais has added: behind you, there will be a lot of people! My ddain heart, but always smiled and said to you, wait for me behind someone, you marry me! But you look carefully: No, other when my wife is the third woman, and do! After a month, I'm in a diffrent place, a different time, different people see you proudly same sentence: I husband my wife when we took over, have you? Did it! I know you do not see me, because before me you were afraid to say it, because I'll hit you.[HTML_REMOVED][HTML_REMOVED]

[HTML_REMOVED]replica]dxwbcshqroxpqxagxxzgr]]replica]dxwbcshqroxpqxagxxzgr[HTML_REMOVED] [HTML_REMOVED]replica]dxwbcshqroxpqxagxxzgr]]replica]dxwbcshqroxpqxagxxzgr[HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED]replica]dxwbcshqroxpqxagxxzgr]]replica]dxwbcshqroxpqxagxxzgr[HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED]

Post Comment
Sign In or provide:
Not disclosed
Human Test*
Markdown formatting
powered by durusworks