In Python, every object has its own separate copy of a field or instance variable.
On the other hand, it’s also possible to define class variables. In this case, all objects share the same copy of the class variable.
Class variables may be referenced via self, but are usually referenced via the name of the class.
class Greeter:
greeting = "Hi"
def __init__(self, name):
self._name = name
def greet(self):
print(f"{Greeter.greeting} {self._name}!")
def main():
g1 = Greeter("Bob")
g2 = Greeter("Sarah")
g1.greet()
g2.greet()
if __name__ == "__main__":
main()
Hi Bob!
Hi Sarah!
Class Methods
It’s also possible to create class methods in Python. Ordinary methods are known as instance methods, because they are associated with instances of the class (i.e. objects) and they can access the data of the objects they belong to.
Class methods belong to the class, not to individual objects. They can access class variables, but not instance variables.
Instead of accepting an object reference as their first parameter, they receive a reference to the class. Since class is a keyword in Python, this parameter needs to be given a different name, such as cls.
The @classmethod decorator is used to define a class method.
class Greeter:
greeting = "Hi"
def __init__(self, name):
self._name = name
def greet(self):
print(f"{Greeter.greeting} {self._name}!")
@classmethod
def show_greeting(cls):
print(cls.greeting)
def main():
g1 = Greeter("Bob")
g2 = Greeter("Sarah")
Greeter.show_greeting()
g1.greet()
g2.greet()
if __name__ == "__main__":
main()
Hi
Hi Bob!
Hi Sarah!
Leave a Reply