class Time:
def __init__(self, hours, minutes):
self.hours = hours # why do i need to write these steps?
self.minutes = minutes
3 Answers
self represents the instance of the class.
Therefore, using self.hours and self.minutes you can set the instance attributes of the object of class Time.
- 65,697
- 9
- 111
- 134
Imagine you have:
class MyClass:
def __init__(self, arg1):
self.argument1 = arg1
def print_1(self):
print(self.argument1)
When you create a class like this, the self points to an instance.
instance1 = MyClass("hello")
instance2 = MyClass("bye")
Doing print(instance1.print_1() will print "hello", and print(instance2.print_1() will print "bye"
So, self is a way to differentiate and manage multiple instances of the same class. And different instances will have its own set of different variables.
- 38
- 1
- 4
init is the instance of your class. When a class is called this method will be invoked first with the relevant arguments needs to be passed. self.minutes = minutes you are storing the minutes parameter to a new class variable reference called self.minutes. By convention we use self as the first parameter.
- 1
- 5