Creating class methods
A class method is one that you execute directly from the class without creating an instance of the class. Sometimes you need to create methods that execute from the class, such as the functions you used with the str class to modify strings. The following steps demonstrate how to create and use a class method.-
Open a Python Shell window.
You see the familiar Python prompt.
-
Type the following code (pressing Enter after each line and pressing Enter twice after the last line):
class MyClass: def SayHello(): print("Hello there!")
The example class contains a single defined attribute, SayHello(). This method doesn’t accept any arguments and doesn’t return any values. It simply prints a message as output. However, the method works just fine for demonstration purposes.
-
Type MyClass.SayHello() and press Enter.
The example outputs the expected string. Notice that you didn’t need to create an instance of the class — the method is available immediately for use.
-
Close the Python Shell window.
A class method can work only with class data. It doesn’t know about any data associated with an instance of the class. You can pass it data as an argument, and the method can return information as needed, but it can’t access the instance data. As a consequence, you need to exercise care when creating class methods to ensure that they’re essentially self-contained.
Creating instance methods
An instance method is one that is part of the individual instances. You use instance methods to manipulate the data that the class manages. As a consequence, you can’t use instance methods until you instantiate an object from the class.All instance methods accept a single argument as a minimum, self. The self argument points at the particular instance that the application is using to manipulate data. Without the self argument, the method wouldn’t know which instance data to use. However, self isn’t considered an accessible argument — the value for self is supplied by Python, and you can’t change it as part of calling the method.
The following steps demonstrate how to create and use instance methods in Python.-
Open a Python Shell window.
You see the familiar Python prompt.
-
Type the following code (pressing Enter after each line and pressing Enter twice after the last line):
class MyClass: def SayHello(self): print("Hello there!")
The example class contains a single defined attribute, SayHello(). This method doesn’t accept any special arguments and doesn’t return any values. It simply prints a message as output. However, the method works just fine for demonstration purposes.
-
Type MyInstance = MyClass() and press Enter.
Python creates an instance of MyClass named MyInstance.
-
Type MyInstance.SayHello() and press Enter.
You see this message.
-
Close the Python Shell window.