Attribute

From CS 61A Wiki
Revision as of 14:13, 6 July 2014 by Dickson.tsai (Talk | contribs)


Jump to: navigation, search

An attribute of an object is a piece of data that describes the object, stored within the object as a key-value pair. Given an object, one can ask for the value of a particular key using dot notation.

>>> object.key
value

To access an object's list of attributes, just call the dir() function on the object.

Example of handling attributes

>>> import datetime
>>> date_object = datetime.date
>>> dir(date_object)
['__add__', '__class__', '__delattr__', '__doc__', '__eq__', ..., 'today', 'toordinal', 'weekday', 'year']
>>> date.year
2014

Class vs. instance attributes

@property

AttributeErrors

When one tries to access an attribute of the object that does not exist, Python will raise an AttributeError: 'type_of_obj' object has no attribute 'key'.

'Nonetype' has no attribute

This error occurs when the object to the left of the dot notation is None.

>>> class Foo():
...     def bar(self):
...         print(3)
...
>>> a = Foo()
>>> b = a.bar()
3
>>> b.bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'bar'

Naming conventions

  • _single_leading_underscore indicates that the attribute should be only be used internally by the object.
  • __double_leading_and_trailing__underscores__ denote "magic" attributes, built-in attributes in Python that have a particular meaning beyond just holding a key-value pair.


Sources