First page Back Continue Last page Overview Graphics
Methods in Classes, 2
- Instead of defining a function outside of a class definition and binding it to a class attribute, we define a method directly inside (indented) of a class definition.
- A method is “just” a function which is defined inside of a class.
- The first parameter is used a reference to the calling instance.
- This parameter is usually called self.
- Self corresponds to the Robot object x.
class Robot:
def say_hi(self):
print("Hi, I am " + self.name)
x = Robot()
x.name = "Marvin"
x.say_hi()
# we can also call it like this:
Robot.say_hi(x)
Problem of the previous class definition:
After having initialised a Robot robot, we shouldn't forget to assign a name to the robot in an additional statement.