class Shape:
def __init__(self):
self.sides = 0
def getArea(self):
pass
why sometime self are pass into bracket as parameter and sometime none ?
class Shape:
def __init__(self):
self.sides = 0
def getArea(self):
pass
why sometime self are pass into bracket as parameter and sometime none ?
Hi @Sean_Chrollo,
In object-oriented programming (OOP) with Python, the use of self
as a parameter in class methods is a common practice, but it’s important to understand when and why it is used.
When self
is Passed as a Parameter:
When we define methods within a class, we typically include self
as the first parameter in these methods. self
is a reference to the instance of the class. When a method is called on an instance of the class, Python automatically passes that instance as the self
parameter. This allows us to access and manipulate instance-specific attributes and methods. For example, the __init__
method in the Shape
, Rectangle
, and Circle
classes accepts self
as the first parameter. When an object of one of these classes is created, self
refers to that specific object, and we can use it to set and access object-specific attributes (like self.width
and self.height
in the Rectangle
class).
When self
is Not Passed as a Parameter:
In some methods, you may see self
not explicitly passed as a parameter. This is because Python automatically handles passing self
when the method is called on an instance. So, when we call some_instance.some_method()
, Python internally passes some_instance
as self
to some_method
.
For example, in your getArea
methods in the Rectangle
and Circle
classes, you don’t see self
as a parameter in the method definition, but it is still accessible within the method because it refers to the instance on which the method is called.
I hope that helps.
Regards!