When should I create a new method vs placing it in init?

When do you create a new method and when do you put it in the __init__? I understand that if it’s a long method it’s better but when you can return it in a single function is there any reason why we would make more methods? I think this looks a lot cleaner:


 class Diameter():
    pi = 3.14159
    def __init__(self, diameter):
        self.radius = diameter/2
        self.area = Diameter.pi * self.radius ** 2
        self.circumference = Diameter.pi * self.radius * 2

        
pizza = Diameter(12)

print(f"Pizza radius: {pizza.radius}")
print(f"Pizza area: {pizza.area}")
print(f"Pizza circumference: {pizza.circumference}")

__init__() is called when you instantiate a class:

Diameter() # create class instance which will trigger the init method

separation of concerns, easier to test.

also, what if you change the diameter:

class Diameter():
    pi = 3.14159
    def __init__(self, diameter):
        self.radius = diameter/2
        self.area = Diameter.pi * self.radius ** 2
        self.circumference = Diameter.pi * self.radius * 2

        
pizza = Diameter(12)

print(f"Pizza radius: {pizza.radius}")
print(f"Pizza area: {pizza.area}")
print(f"Pizza circumference: {pizza.circumference}")

pizza.radius = 500

print(f"Pizza radius: {pizza.radius}")
print(f"Pizza area: {pizza.area}")
print(f"Pizza circumference: {pizza.circumference}")

then you have a bug. instance properties can change, thus you can’t rely on the fact that you can instantiate a class once and that everything will stay the same, so you can’t push everything in the init method

1 Like

Thank you, you made it very clear!