Why does my function know a value of an attribute without a assignment rule?

51 views Asked by At

I've started learning Python recently and got this code here:

import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2

    @staticmethod
    def convert_area_in_radius(area):
        return math.sqrt(area/math.pi)


c2 = Circle(Circle.convert_area_in_radius(80))

print(c2.radius)

If I run my console the return is 5.04..

That makes sense for me because of calling the def convert_area_in_radius. But where does Python know it is assigned to the attribute radius of the init method? I mean I am calling

print(c2.radius)

there is know reference to this attribute radius

I expected to get the same return but not with calling print(c2.radius)

1

There are 1 answers

0
cards On

You are nesting expressions. Here a "denested" version

# using a "function" associated to the class 
r = Circle.convert_area_in_radius(80)

# creating the instance
c2 = Circle(r)

# access to the attribute of the instance
print(c2.radius)
#5.046265044040321

# call the method of the instance
print(c2.area())
#80.00000000000001 # almost the original (due to pi, or in general to float-limitations)

A convert_area_in_radius is a static method has no explicit information about the neither of instance nor the class it belongs to.

Instead area is method that is bound the the instance and that's why you need to pass a self parameter.