简体   繁体   中英

Calling function in inside another function

I am create this function

def volumn(value_side):

    def side(value_side):
        side = value_side+2
        return (side)

    value_area = side(value_side)

    def area(value_area):
        area = value_area*4
        return(area)

    final_result = area(value_area)
    return(final_result)

My question is How If I just want to call side function

I have try with this code volumn(3).side(3) but still error int' object has no attribute 'side'

You can return the inner functions side and area to access them outside

def volumn():

    def side(value_side):
        side = value_side+2
        return side

    def area(value_area):
        area = value_area*4
        return(area)

    return side, area


side, area = volumn()
side_value = side(3)
print(side_value)
print(area(side_value))

Or you can use a class to encapsulate the functions and attributes

class Volumn:

    def __init__(self, value_side):
        self.value_side = value_side

    def side(self):
        side = self.value_side+2
        return side

    def area(self):
        area = self.side()*4
        return area

v = Volumn(3)
print(v.side())
print(v.area())

The output will be

5
20

You could define these functions in the outer scope to access them.

def side(value_side):
    side = value_side+2
    return (side)


def area(value_area):
    area = value_area*4
    return(area)


def volume(value_side):
    value_area = side(value_side)
    final_result = area(value_area)
    return final_result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM