Reputation: 1
Ive been working on this sample code for a while and cant seem to wrap my head around this seemingly simple error.
The code is as follows:
class area :
r=5
l=2
b=3
def __init__(self,r,l,b):
print "parent constructor"
self.r=r
self.l=l
self.b=b
def __del__(self):
print "parent deconstructor"
def circle(self):
circle_area= 3.14 * r * r
print "area of circle is :",circle_area
def rectangle(self):
rect_area=l*b
print "area of rectangle :",rect_area
obj=area(4,5,4)
obj2=area(2,5,4)
obj.circle()
The error message says :
File "yaa.py", line 18, in circle
circle_area= 3.14 * r * r
NameError: global name 'r' is not defined.
Upvotes: 0
Views: 9307
Reputation: 42716
You need to use the self for refering class attributes:
def circle(self):
circle_area= 3.14 * self.r * self.r
print "area of circle is :",circle_area
In case you want to use the r
within the class, not the instance you have to use the name of the class then:
def circle(self):
circle_area= 3.14 * area.r * area.r
print "area of circle is :",circle_area
Upvotes: 3
Reputation: 16505
You probably need to change your method circle(self)
from
circle_area= 3.14 * r * r
to
circle_area= 3.14 * self.r * self.r
because r
is an attribute of the class, not a global variable.
The same goes for your method rectangle(self)
:
rect_area = self.l * self.b
Upvotes: 1