Why is it considered bad practice to hard code the class name inside class methods?

In python, why is it bad 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 can be defined as follows:

def area(self): return self.__class__.pi * squared(self.radius) 

which, if I'm not mistaken, is considered the best way to refer to a class variable. The question is why? Intuitively, I don't like it, but I don't seem to understand it completely.

+4
source share
4 answers

Why is it considered that bad practice rigidly sets the class name inside class methods?

This is not true. I don’t know why you think so.

There are many good reasons for hard coding a class name inside its methods. For example, using superin Python 2:

super(ClassName, self).whatever()

super(self.__class__, self).whatever(), , . , super, self.__class__, .

- . , , , , :

class Foo(object):
    def big_complicated_calculation(self):
        return # some horrible mess
    def slightly_different_calculation(self):
        return self.big_complicated_calculation() + 2

, slightly_different_calculation big_complicated_calculation, Foo.big_complicated_calculation:

def slightly_different_calculation(self):
    return Foo.big_complicated_calculation(self) + 2

, ClassName.whatever self.whatever self.__class__.whatever.

+2

, , , . , :

class Rectangle(object):
    name = "Rectangle"
    def print_name(self):
        print(self.__class__.name) # or print(type(self).name)

class Square(Rectangle):
    name = "Square"

Square print_name, "". Rectangle.name self.__class__.name ( type(self).name), "Rectangle".

+4

.

class WeirdCircle(Circle):
    pi = 4

c = WeirdCircle()
print(c.area()) 
# returning 4 with self.__class__.pi 
# and 3.14159 with Circle.pi

, .

+2

Zen python , , , . . self, . . .

class Rectangle(object):
    self.name = "Rectangle"
    def print_name(self):
        print(self.name)

class Square(Rectangle):
    name = 'square'

sq = Square()
sq.print_name
0

Source: https://habr.com/ru/post/1654059/


All Articles