Python for Java Programmers
Chapter 8: Object-oriented programming
Class and static methods
You might have used static methods in Java.
In Python, static methods are called class methods.
A class method is bound to the class and not to the class instance.
Therefore, a class method takes the class (cls
) as its first argument, rather than the class instance (self
) as in an instance method.
Thus, class methods do not have access to the object instance (via self
), but only the class (via cls
). Therefore, it does not have access to any instance attributes or methods.
You will also need to annotate the method with a @classmethod
decorator (Line 9). This decorator informs Python that cls
is a class, and not an instance!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
You can access a class method with either the ClassName
(Line 14) or an instance_name
(Line 15).
When Line 14 is executed, Python will pass Person
as the first parameter cls
. Therefore, cls.count
(Line 11) is actually Person.count
.
When Line 15 is executed, the same will happen. Python will figure out that lecturer
is an instance of Person
. Since get_population()
is annotated as a class method, Python will pass the class name Person
as the first parameter instead of the lecturer
instance.
(Python) static methods
Just to make things more confusing, Python also offers what it calls a static method. Note that this is slightly different from static methods in Java! A Python static method basically acts like a normal function, except that it is defined inside the scope of a class. Note that there is no compulsory first parameter self
or cls
here - it’s just a normal function! Like a class method, use a @staticmethod
decorator to make a method static; this tells Python not to pass self
or cls
as the first argument in the method call.
1 2 3 4 5 6 7 8 9 10 11 |
|