Defining Class Attributes and Methods
Any variable that is bound in a class is a class attribute.
Any function defined within a class is a method. Methods
receive an instance of the class, conventionally called self
,
as the first argument. For example, to define some class attributes
and methods, you might enter the following code:
class MyClass
attr1 = 10 #class attributes
attr2 = "hello"
def method1(self):
print MyClass.attr1 #reference the class attribute
def method2(self):
print MyClass.attr2 #reference the class attribute
def method3(self, text):
self.text = text #instance attribute
print text, self.text #print my argument and my attribute
method4 = method3 #make an alias for method3
Inside a class, you should qualify all references to class attributes
with the class name; for example, MyClass.attr1
.
All references to instance attributes should be qualified with the self
variable;
for example, self.text
. Outside the class, you should
qualify all references to class attributes with the class name (for
example MyClass.attr1
) or with an instance of the
class (for example x.attr1
, where x
is
an instance of the class). Outside the class, all references to instance
variables should be qualified with an instance of the class; for example, x.text
.