I’m learning Python OOP now and confused with somethings in the code below.
Questions:
-
def __init__(self, radius=1):
What does the argument/attribute “radius = 1” mean exactly?
Why isn’t it just called “radius”? -
The method area() has no argument/attribute “radius”.
Where does it get its “radius” from in the code?
How does it know that the radius is 5?class Circle: pi = 3.141592 def __init__(self, radius=1): self.radius = radius def area(self): return self.radius * self.radius * Circle.pi def setRadius(self, radius): self.radius = radius def getRadius(self): return self.radius c = Circle() c.setRadius(5)
Also,
-
In the code below, why is the attribute/argument
namemissing in the brackets? -
Why was is not written like this:
def __init__(self, name)
anddef getName(self, name)?class Methods: def __init__(self): self.name = 'Methods' def getName(self): return self.name
This is default value setting to initialize a variable for the class scope.This is to avoid any garbage output in case some user calls
c.Area()right afterc = Circle().In the line
self.name = 'Methods'you are creating a variablenameinitialized to string valueMethods.self.nameis defined for the class scope. You can get and set its value anywhere inside the class.