Show More
@@ -76,3 +76,37 b' specific ``IPY`` or ``ipy`` are preferred.' | |||
|
76 | 76 | |
|
77 | 77 | .. [PEP8] Python Enhancement Proposal 8. http://www.python.org/peps/pep-0008.html |
|
78 | 78 | |
|
79 | Attribute declarations for objects | |
|
80 | ================================== | |
|
81 | ||
|
82 | In general, objects should declare in their *class* all attributes the object | |
|
83 | is meant to hold throughout its life. While Python allows you to add an | |
|
84 | attribute to an instance at any point in time, this makes the code harder to | |
|
85 | read and requires methods to constantly use checks with hasattr() or try/except | |
|
86 | calls. By declaring all attributes of the object in the class header, there is | |
|
87 | a single place one can refer to for understanding the object's data interface, | |
|
88 | where comments can explain the role of each variable and when possible, | |
|
89 | sensible deafaults can be assigned. | |
|
90 | ||
|
91 | .. Warning:: | |
|
92 | ||
|
93 | If an attribute is meant to contain a mutable object, it should be set to | |
|
94 | ``None`` in the class and its mutable value should be set in the object's | |
|
95 | constructor. Since class attributes are shared by all instances, failure | |
|
96 | to do this can lead to difficult to track bugs. But you should still set | |
|
97 | it in the class declaration so the interface specification is complete and | |
|
98 | documdented in one place. | |
|
99 | ||
|
100 | A simple example:: | |
|
101 | ||
|
102 | class foo: | |
|
103 | # X does..., sensible default given: | |
|
104 | x = 1 | |
|
105 | # y does..., default will be set by constructor | |
|
106 | y = None | |
|
107 | # z starts as an empty list, must be set in constructor | |
|
108 | z = None | |
|
109 | ||
|
110 | def __init__(self, y): | |
|
111 | self.y = y | |
|
112 | self.z = [] |
General Comments 0
You need to be logged in to leave comments.
Login now