Ankur Agarwal
Ankur Agarwal

Reputation: 24758

Class member variable visibility in instance methods

>>> class Triangle(object):
...     number_of_sides = 3
...     def __init__(self, angle1, angle2, angle3):
...         self.angle1 = angle1
...         self.angle2 = angle2
...         self.angle3 = angle3
...     def check_angles(self):
...         return True if self.angle1 + self.angle2 + self.angle3 == 180 else False
... 
>>> class Equilateral(Triangle):
...     angle = 60
...     def __init__(self):
...         self.angle1 = angle
...         self.angle2 = angle
...         self.angle3 = angle
... 
>>> 
>>> e = Equilateral()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
NameError: global name 'angle' is not defined

Surprisingly this piece of code gave an exception. Why is angle found to be not defined ??

The question is not how can I access angle, the question is why is angle not accessible ?

Upvotes: 0

Views: 82

Answers (2)

hxysayhi
hxysayhi

Reputation: 1987

Maybe you can use self.angle

just like this:

class Equilateral(Triangle):
     angle = 60
     def __init__(self):
         self.angle1 = self.angle
         self.angle2 = self.angle
         self.angle3 = self.angle

But I think the first answer is better,(I saw it after I submitted my answer).My answer can work because the init() will go to find the angle of my class when it can't find angle of my object. Here is a demo:

class test():
    angle = 0
    def __init__(self):
        self.angle1 = self.angle  # when __init__() run,it can't find a angle of your object,
                                  # so it will go to find the global angle in your class

    def show(self):
        print self.angle1

    def change(self):
        self.angle = 1   # this self.angle is a val of the object
        print self.angle

    def change_class(self):
        test.angle = 1   # if you want to change the angle of your class,this can be worked

a = test()
a.show()
a.change()
b = test()
b.show()
b.chenge_class()
c = test()
c.show()

Upvotes: 2

Alex Boxall
Alex Boxall

Reputation: 571

Try using Equilateral.angle instead of angle.

class Equilateral(Triangle):
    angle = 60
    def __init__(self):
        self.angle1 = Equilateral.angle
        self.angle2 = Equilateral.angle
        self.angle3 = Equilateral.angle

Upvotes: 2

Related Questions