Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

python - Limit a method to be called only through another method?

Say i have two methods first_method and second_method as follows.

def first_method(some_arg):
    """
    This is the method that calls the second_method
    """

    return second_method(some_arg[1], some_arg[2])


def second_method(arg1, arg2):
    """
    This method can only be called from the first_method
    or it will raise an error.
    """

    if (some condition):
        #Execute the second_method
    else:
        raise SomeError("You are not authorized to call me!")

How can i check (what condition(s)) that second method is being called by the first method and process the method according to that ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why don't you define the second method within first method, so that its not exposed to be called directly.

example:

def first_method(some_arg):
    """
    This is the method that calls the second_method
    """
    def second_method(arg1, arg2):
        """
        This method can only be called from the first_method
        hence defined here
        """

        #Execute the second_method


    return second_method(some_arg[1], some_arg[2])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...