Write a program using an object
Start to create your object-oriented text-based adventure game
Extend other people’s classes
Create an enemy in the room
Recap Week 3
Extending your knowledge of OOP
Finish your game
End of the course
During this course you have been using methods to interact with instances (objects) of classes. These methods are known as instance methods. There are two other types of method available in Python: static and class. In this step you will explore the different types of method and how they can be used.
When you define a method, the first parameter of the method is named self and refers to the object that called the method, for example:
class MyClass():
def instance_method(self):
print(self)
To use a method you must first create an instance (object) of the class. For example:
my_object = MyClass()
my_object.instance_method()
Static and class methods are different to instance methods in that you don’t have to create an object of the class before you can use them. Static and class methods belongs to a class, whereas an instance methods belongs to the object.
Static and class method are useful if you want to create a function that is the same for all objects within a class.
Review the code below, which includes a static method and a class method in addition to an instance method.
class MyClass():
def instance_method(self):
print(self)
@staticmethod
def static_method():
print("nothing")
@classmethod
def class_method(cls):
print(cls)
my_object = MyClass()
my_object.instance_method()
MyClass.static_method()
MyClass.class_method()
This code demonstrates that:
An instance method is passed self, a static method is passed nothing, and a class method is passed cls, which is the class the method belongs to.
To define a method as static or class, you use either the @staticmethod or @classmethod decorator.
You call a static or class method via the class (MyClass.staticmethod()), not its object.
In the next step you will use instance, static, and class methods to create a class to describe your role-playing game.
What scenarios can you think of for using static or class methods in your game? Share your thoughts in the comments section.