Difference between revisions of "Attribute"

From CS 61A Wiki
Jump to: navigation, search
[checked revision][checked revision]
m (copyedit)
(copyedit; reorganize)
Line 7: Line 7:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
== List of attributes ==
+
==Class attribute==
To access an object's list of attributes, call the <code>dir()</code> function on the object. Example:
+
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:
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
>>> import datetime
+
>>> class A:
>>> date_object = datetime.date
+
...    class_attribute = 5
>>> dir(date_object)
+
...  
['__add__', '__class__', '__delattr__', '__doc__', '__eq__', ..., 'today', 'toordinal', 'weekday', 'year']
+
>>> A.class_attribute
>>> date.year
+
5
2014
+
>>> A().class_attribute
 +
5
 
</syntaxhighlight>
 
</syntaxhighlight>
  
===Class attribute===
+
<!--
Attributes defined within a class but outside of methods are ''class attributes''. Class attributes, which include methods, can be accessed by the class or by instances of the class. Class attributes are 'shared' by all instances and the class itself, unless overridden or overwritten by an instance attribute. When a class attribute is changed, all instances and classes that access it will see the change, regardless of what object made the change. Classes that use assignment statements with dot expressions will set a class attribute.
+
 
+
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
>>> class Test():
 
>>> class Test():
Line 43: Line 44:
 
0
 
0
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
-->
  
 
==Instance attribute==
 
==Instance attribute==
Attributes defined inside methods are ''instance attributes''. Instance attributes are locally defined and can only be accessed by their respective instances. The value of an instance attribute is 'unique' to each instance, and 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 then only access the instance attribute, although the class can still access the class attribute. Instances that use assignment statements will set instance attributes.
+
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.
 +
 +
Example:
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
>>> class Test():
+
>>> class A:
 
         num = 0
 
         num = 0
 +
 
         def __init__(self):
 
         def __init__(self):
 
             self.num = 1
 
             self.num = 1
 +
 
         def increase(self):
 
         def increase(self):
 
             self.num += 1
 
             self.num += 1
>>> Test.num
+
>>> A.num
 
0
 
0
>>> inst1 = Test()
+
>>> inst1 = A()
>>> inst2 = Test()
+
>>> inst2 = A()
 
>>> inst1.num
 
>>> inst1.num
 
1
 
1
Line 67: Line 74:
 
>>> inst2.num
 
>>> inst2.num
 
1
 
1
 +
>>> A.num
 +
0
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 80: Line 89:
 
>>> inst.char
 
>>> inst.char
 
'b'  
 
'b'  
 +
>>> Test.char
 +
'a'
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 112: Line 123:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
== @property ==
+
== <code>@property</code> ==
The property decorator is another way of having a getter and setter method for a defined class. It has three methods a [[Getter|getter]], a [[Setter|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.)
+
<code>@property</code> is a shorthand way to create getter and setter methods. Putting <code>@property</code> above a method allows it to be accessed as if it were an instance variable.
  
Here's an example:
+
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.<ref>http://markmiyashita.com/cs61a/object_oriented_programming/property/</ref>
 +
 
 +
Example:
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
class ImAClass(object):
+
class Square:
 
+
     def __init__(self, side_length):
     def __init__(self):
+
         self._length = side_length # leading underscore indicates that this attribute is only for internal use
         self._Property = None
+
 
+
  
 
     @property
 
     @property
     def Property(self):
+
     def area(self):
        """I am a property."""
+
         return self._length ** 2
         return self._Property
+
  
 +
    @area.setter
 +
    def area(self, value):
 +
        self._length = value ** (1/2)
  
    @Property.setter
+
>>> sq = Square(5.0)
    def Property(self, value):
+
</syntaxhighlight>
        self._Property = value
+
Because <code>area</code> is a <code>property</code> method, it can be accessed by <code>sq.area</code> instead of <code>sq.area()</code>:
 
+
<syntaxhighlight lang="python">
 
+
>>> sq.area
    @Property.deleter
+
25.0
    def Property(self):
+
        del self._Property
+
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 +
The second <code>area</code> method is marked as a setter method for the property <code>area</code>, so it is called when we use attribute assignment:
 +
<syntaxhighlight lang="python">
 +
>>> sq.area = 9.0
 +
>>> sq.area
 +
9.0
 +
>>> sq._length
 +
3.0
 +
</syntaxhighlight>
 +
<!--
 
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.  
 
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.  
  
Line 176: Line 196:
  
 
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.
 
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.
 
+
-->
 
== AttributeError ==
 
== AttributeError ==
 
When one tries to access an attribute of the object that does not exist, Python will raise an <code>AttributeError: 'type_of_obj' object has no attribute 'key'</code>.
 
When one tries to access an attribute of the object that does not exist, Python will raise an <code>AttributeError: 'type_of_obj' object has no attribute 'key'</code>.
  
=== 'Nonetype' has no attribute ===
+
This error commonly occurs when the object to the left of the dot is <code>None</code>. Example:
This error occurs when the object to the left of the dot notation is <code>None</code>.
+
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
>>> class Foo():
+
>>> obj = None
...    def bar(self):
+
>>> obj.a()
...        print(3)
+
...
+
>>> a = Foo()
+
>>> b = a.bar()
+
3
+
>>> b.bar()
+
 
Traceback (most recent call last):
 
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
+
   ...
AttributeError: 'NoneType' object has no attribute 'bar'
+
AttributeError: 'NoneType' object has no attribute 'a'
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 
== Naming conventions<ref>http://legacy.python.org/dev/peps/pep-0008 PEP 8 Style Guide for Python Code</ref> ==
 
== Naming conventions<ref>http://legacy.python.org/dev/peps/pep-0008 PEP 8 Style Guide for Python Code</ref> ==
* _single_leading_underscore indicates that the attribute should be only be used internally by the object.
+
* <code>_single_leading_underscore</code> indicates that the attribute should be only be used internally by the object.
* __double_leading_and_trailing__underscores__ denote [[Magic method|"magic" attributes]], built-in attributes in Python that have a particular meaning beyond just holding a key-value pair.
+
* <code>__double_leading_and_trailing__underscores__</code> denote [[magic method]]s, built-in attributes in Python that have a particular meaning beyond just holding a key-value pair.
  
 
== Implementation ==
 
== Implementation ==

Revision as of 14:09, 24 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 an attribute using dot notation.

>>> object.attribute
value

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
5
>>> A().class_attribute
5


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.

Example:

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

Method

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):
            self.id = id
        def useless_method():
            return 5
        def example_method(self):
            return self.id
>>> 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()
5
>>> a.example_method()
6
>>> b = A(7)
>>> b.example_method()
7
>>> A.example_method(a)
6

@property

@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]

Example:

class Square:
    def __init__(self, side_length):
        self._length = side_length # leading underscore indicates that this attribute is only for internal use
 
    @property
    def area(self):
        return self._length ** 2
 
    @area.setter
    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
25.0

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
9.0
>>> sq._length
3.0

AttributeError

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.

Implementation

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]
            else:
                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

References

  1. http://markmiyashita.com/cs61a/object_oriented_programming/property/
  2. http://legacy.python.org/dev/peps/pep-0008 PEP 8 Style Guide for Python Code
  3. http://composingprograms.com/pages/26-implementing-classes-and-objects.html#instances Implementation of attributes in Python