Summary - Static and class methods
- Python course
- Intermediate
- Lesson 29/116
- 5 min
Combine @staticmethod, @classmethod and constants to write a Configuration class.
Summary - Static and class methods
In this group we covered @staticmethod, @classmethod, the factory pattern, class variables and constants. A static method has no self; a class method takes cls.
A factory method returns a new instance; it is named with a from_ prefix. A class variable is shared by all instances. Constants use uppercase. Now we'll combine these into a Bank class.
Practice Combine the Bank class
Define the Bank class. Add the class variable interest_rate = 0.05 in the body. Add @classmethod and def set_rate(cls, rate):; in the body write cls.interest_rate = rate. Add @staticmethod and def describe():; in the body write return "Bank". Then call Bank.set_rate(0.07) and print(Bank.interest_rate).
Starter code
# Combine the Bank classSample solution
# Combine the Bank class
class Bank:
interest_rate = 0.05
@classmethod
def set_rate(cls, rate):
cls.interest_rate = rate
@staticmethod
def describe():
return "Bank"
Bank.set_rate(0.07)
print(Bank.interest_rate)Expected output
0.07
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the first parameter of @classmethod?
- self
- class
- this
- cls Correct answer
Explanation: The first parameter of @classmethod is cls.
2 Match the concepts
| Term | Meaning |
|---|---|
@staticmethod |
Selfless |
@classmethod |
With cls |
from_list |
Factory |
3 Complete the class variable
class Bank:
____ = 0.05
class Bank:
interest_rate = 0.05
Explanation: interest_rate is written directly in the body.