In python, why is it a bad thing to do something like this:
class Circle:
pi = 3.14159 # class variable
def __init__(self, r = 1):
self.radius = r
def area(self):
return Circle.pi * squared(self.radius)
def squared(base): return pow(base, 2)
The area method could be defined as follows:
def area(self): return self.__class__.pi * squared(self.radius)
which is, unless I'm very much mistaken, considered a better way to reference a class variable. The question is why? Intuitively, I don't like it but I don't seem to completely understand this.
Because in case you subclass the class it will no longer refer to the class, but its parent. In your case it really doesn't make a difference, but in many cases it does:
class Rectangle(object):
name = "Rectangle"
def print_name(self):
print(self.__class__.name) # or print(type(self).name)
class Square(Rectangle):
name = "Square"
If you instantiate Square
and then call its print_name
method, it'll print "Square". If you'd use Rectangle.name
instead of self.__class__.name
(or type(self).name
), it'd print "Rectangle".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With