0
Guys , whatâs wrong with this code
class Shape: def __init__(self, w, h): self.width = w self.height = h def area(self): print(w*h) class Rectangle(shape): #your code goes here def perimter(self): print(2*(w+h)) w = int(input()) h = int(input()) r = Shape(w, h) r.area() r.perimeter()
5 Answers
+ 5
class Shape:
def __init__(self, wd, ht):
self.width = wd
self.height = ht
def area(self):
print(self.width*self.height) #1
class Rectangle(Shape):
#your code goes here
def perimeter(self): #spell check
print(2*(self.width+self.height))
w = int(input())
h = int(input())
r = Rectangle(w, h) #Rectangle class object
r.area()
r.perimeter() #rectangle method
#read comment for corrections info.
#reply if not understood...
+ 5
47/PROđ Class "Rectangle" inherits from "shape", but the only defined class is "Shape".
Object "r" is instantiated from "Shape", but you call methods from "Rectangle".
Methods "area" and "perimeter" use variables w and h, but they are not defined inside the classes. You probably mean to use object attributes, and not variables.
+ 4
Jayakrishna đźđł Sam Pls avoid giving finished code as answer, because it makes the OP skip the most important part of learning, and encourage the bad habit of asking for others to solve one's tasks. Prefer giving hints for the OP to find the solution instead.
+ 1
Emerson Prado yes. That's true.
And most important part of learning is "attempting" , "practice" . OP ran through it already.
There is only 2 main small mistakes only. Depending on the level of attempt, i thought OP can understand and find his/her mistakes easily so i given corrected code with hints in comments as explanation. Asked to reply if anything not understood.
I think, it's not a fees spoon solution or readymade code. Just a 2 line modified code.
Instead of it, i need to explain about variable scope, Inheritance .. It goes to vain if OP knows already. Iam waiting OP response to understand level for further if need.
Here, instead i choose simplest, corrected code only helps in finding mistake. And that's enough i think.
I never post solution only replies..
0
class Shape:
def __init__(self, w, h):
self.width = w
self.height = h
def area(self):
print(self.width * self.height)
class Rectangle(Shape):
def perimeter(self):
print(2 * (self.width + self.height))
w = int(input())
h = int(input())
r = Rectangle(w, h)
r.area()
r.perimeter()