Defining class attributes and methods
Any variable that's 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
, as the first argument. For example, to define some class attributes
and methods, you might enter the following script:self
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,
). All references to instance attributes should be qualified
with the MyClass.attr1
variable (for example, self
). Outside the
class, you should qualify all references to class attributes with the class name (for example,
self.text
) or with an instance of the class (for example,
MyClass.attr1
, where x.attr1
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
).x.text