Class and Instance Attributes
An attribute set in __init__ with self belongs to one object. An attribute written directly in the class body is shared by every object. @classmethod works with the class and @staticmethod is a plain function stored in the class.
Example
class Account:
bank = "Justice Bank"
def __init__(self, owner):
self.owner = owner
@classmethod
def rename_bank(cls, name):
cls.bank = name
@staticmethod
def valid(amount):
return amount > 0
a, b = Account("Ada"), Account("Tunde")
print(a.bank, b.bank)
Account.rename_bank("New Bank")
print(a.bank, b.owner)
print(Account.valid(-5))Result
Justice Bank Justice Bank New Bank Tunde False
Exercise
Mark a method that receives the class.
classmethod
def make(cls):
passQuiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.