Tuesday, February 26, 2013

Data Attributes


While data attributes defined both ways may have unique values for any particular instance, those that exist in the class definition can be accessed without an instance of the class, as the following hypothetical example:
import sys;
class NewClass():
    data_attribute1 = 1;
    def __init__(self):
        self.data_attribute2 = 2;
print(NewClass.data_attribute1);
try:
    print(NewClass.data_attribute2);
except AttributeError:
    print(sys.exc_info()[0]);
instance = NewClass();
print(instance.data_attribute1);
print(instance.data_attribute2);
1
<type 'exceptions.AttributeError'>
1
2

No comments:

Post a Comment