The main con / gotcha using class attributes to provide default values for what you intend to use for specific instances is that the default values will be shared among all instances of the class until the value is changed. For example:.
class Foo(object): a = [] foo1 = Foo() foo2 = Foo() foo1.a.append(123) foo1.a
However, as expected, the following will work:
class Bar(object): a = 123 bar1 = Bar() bar2 = Bar() bar1.a = 456 bar2.a
To avoid this error when using this technique, you should only use it to set default values that are immutable. (For example, numbers, strings, tuples ...)
The reason Python behaves this way is because when accessing an attribute with:
foo.bar
then bar first scanned in the foo object. If the name is not found in the object (i.e. In foo.__dict__ ), then the name is looked up in the type of this object. For example, this mechanism is part of the work of search methods. (If you look at the __dict__ object, you will notice that its methods are missing there).
Other minor problems are that it provides default values through a type object when they are intended for instance specificity; and that it mixes class-specific attribute definitions (like constants) if you have default values. The consequence of the first is that this will allow you to override the default value later for all objects that have not yet changed the value by assigning a class attribute. (This can be useful or confusing; the same precaution applies to mutable "global" variables.)
millimoose
source share