From CS 61A Wiki
Revision as of 14:09, 24 July 2014 by Axis (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 an attribute using dot notation.

>>> object.attribute

Class attribute

A class attribute is shared by all instances of a class. Class attributes are defined within the class but outside of methods.

They can be accessed by the class or by instances of the class. Example:

>>> class A:
...     class_attribute = 5
>>> A.class_attribute
>>> A().class_attribute

Instance attribute

An instance attribute is specific to one instance of a class. Instance attributes are typically defined inside methods.

Changes to an instance attribute can only be seen by its instance. If a class attribute and instance attribute have the same variable name, then the instance attribute will hide the class attribute. The instance can only access the instance attribute, although the class can still access the class attribute.


>>> class A:
        num = 0
        def __init__(self):
            self.num = 1
        def increase(self):
            self.num += 1
>>> A.num
>>> inst1 = A()
>>> inst2 = A()
>>> inst1.num
>>> inst2.num
>>> inst1.increase()
>>> inst1.num
>>> inst2.num
>>> A.num
>>> class Test():
        char = 'a'
>>> Test.char
>>> inst = Test()
>>> inst.char
>>> inst.char = 'b'
>>> inst.char
>>> Test.char


A method is an attribute of an instance (not of a class) where the value is a function that manipulates the object. Unlike regular functions, methods are invoked on an object via dot notation, so the object that the method is invoked on will be automatically passed into the method as an argument. Note that accessing the attribute from the class will only return the function, so the object argument must be passed in instead of being omitted via dot notation.

>>> class A():
        def __init__(self, id):
   = id
        def useless_method():
            return 5
        def example_method(self):
>>> a = A(6)
>>> a.useless_method
<bound method A.useless_method of <__main__.A object at 0xe10250>>
>>> a.useless_method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: useless_method() takes no arguments (1 given)
>>> A.useless_method
<function useless_method at 0xe0ed10>
>>> A.useless_method()
>>> a.example_method()
>>> b = A(7)
>>> b.example_method()
>>> A.example_method(a)


@property is a shorthand way to create getter and setter methods. Putting @property above a method allows it to be accessed as if it were an instance variable.

Sometimes we have a value that can be computed by accessing other instance variables. Instead of defining a new instance variable (which would then have to be modified each time we change an existing instance variable), we simply make a property.[1]


class Square:
    def __init__(self, side_length):
        self._length = side_length # leading underscore indicates that this attribute is only for internal use
    def area(self):
        return self._length ** 2
    def area(self, value):
        self._length = value ** (1/2)
>>> sq = Square(5.0)

Because area is a property method, it can be accessed by sq.area instead of sq.area():

>>> sq.area

The second area method is marked as a setter method for the property area, so it is called when we use attribute assignment:

>>> sq.area = 9.0
>>> sq.area
>>> sq._length


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'.

This error commonly occurs when the object to the left of the dot is None. Example:

>>> obj = None
>>> obj.a()
Traceback (most recent call last):
AttributeError: 'NoneType' object has no attribute 'a'

Naming conventions[2]

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


In a Python functional implementation of object-oriented programming, attributes can be modeled as a local dictionary within the object frame[3], because attributes are just key-value pairs belonging to the object.

>>> # From Section 2.6.1 of Composing Programs by John DeNero (see citation above)
>>> def make_instance(cls):
        """Return a new object instance, which is a dispatch dictionary."""
        def get_value(name):
            if name in attributes:
                return attributes[name]
                value = cls['get'](name)
                return bind_method(value, instance)
        def set_value(name, value):
            attributes[name] = value
        attributes = {}
        instance = {'get': get_value, 'set': set_value}
        return instance


  2. PEP 8 Style Guide for Python Code
  3. Implementation of attributes in Python