Difference between revisions of "Attribute"

From CS 61A Wiki
Jump to: navigation, search
[checked revision][checked revision]
Line 108: Line 108:
== Sources ==
== Sources ==
* [http://legacy.python.org/dev/peps/pep-0008 PEP 8 Style Guide for Python Code]
* [http://legacy.python.org/dev/peps/pep-0008 PEP 8 Style Guide for Python Code]
* [http://blaag.haard.se/What-s-the-point-of-properties-in-Python/]

Revision as of 15:16, 6 July 2014

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

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

Class vs. instance attributes


The property object is, simply put, another way of having a getter and setter method for a defined class. It has three methods a getter, a setter, and a deleter (but don't worry about deleters. They are outside the scope of this course and you will not be tested on them.)

Here's an example:

class ImAClass(object):
    def __init__(self):
        self._Property = None
    def Property(self):
        """I am a property."""
        return self._Property
    def Property(self, value):
        self._Property = value
    def Property(self):
        del self._Property

There is little to no difference between implementing a property vs implementing separate getters and setters, and the difference in the amount of code is often negligible.

Here is an example of implementation using getters and setters:

>>> class Get_set_imp(object):
...   val = 0
...   def setter(self, x):
...       self.val = x
...   def getter(self):
...       return self.val
>>> x = Get_set_imp()
>>> x.setter(3)
>>> x.getter()


And here is the same implementation, this time using properties:

>>> class Prop_imp(object):
...   _val = 0
...   @property
...   def getter(self):
...       return self._val
...   @getter.setter
...   def setter(self, x):
...       self._val = x
>>> x = Prop_imp()
>>> x.setter = 10
>>> x.getter

Both of these examples essentially do the same thing in roughly the same amount of code. The advantage of having properties however, is that you may switch from the two whenver you want. Simply add or remove or add the property tags from the getters and setters.


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()
>>> 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.


Cite error: <ref> tags exist, but no <references/> tag was found