#1 First Method
class Triangle(object):
def area(self, b, h):
self.b = b
self.h = h
return b*h/2
a = Triangle()
a.area(4,8)
I tried to write down the code above using the init method.
#2 Try the second method
class Triangle(object):
def __init__(self, value_v, value_h):
b = value_h
h = value_v
def area(self,b,h):
return b*h / 2
a=Triangle()
a.area(4,8)
However, the following error message was received:
8 def area(self,b,h):
9 return b*h / 2
---> 10 a=Triangle()
11 a.area(4,8)
TypeError: __init__() missing 2 required positional arguments: 'value_v' and 'value_h'
.#2 Code
a=Triangle( )
It works well when you get rid of it.
Question 1
Unlike .#1, I wonder why it works well when you get rid of Triangle().
Question 2
class triangle(object):
even if you remove the parentheses from class triangle:
, it goes the same way. I wonder why you put the parentheses.
I'd appreciate it if you could answer
Have a nice day!
init def python
If you use the _init___
method, you must pass the parameter at a=Triangle()
to the parameter after self
in the __init____
method.
It is ideal to use it as below.
class Triangle(object):
def __init__(self, b, h):
self.b = b
self.h = h
def area(self):
return self.b * self.h / 2
a = Triangle(4, 8)
print(a.area())
© 2024 OneMinuteCode. All rights reserved.