首页 > 解决方案 > 如果从命令行调用一个类而不是在代码中调用一个类,python 中是否有办法运行不同的函数?

问题描述

假设我有一个课程如下:

class MyClass:
    def __init__(self):
        pass

    def my_func_1(self):
        print("This class has been invoked from another code")

    def my_func_2(self):
        print("This class has been called from the command prompt")

if __name__ == "__main__":
    MyClass()

有没有办法让类运行 my_func_1 如果它是从代码调用的,而 my_func_2 如果是从命令行调用的?另外,从命令行我的意思是if __name__ == "__main__":部分。

标签: python-3.x

解决方案


我想使用它的上下文是让主类的init读取命令行的访问级别或要求用户登录到管理员用户。我最终传递了一个值,该值仅在从命令行运行代码时才为真。

class MyClass:
    def __init__(self, from_command_line: bool = False):
        if from_command_line:
            my_func_2()
        else:
            my_func_1()

    def my_func_1(self):
        print("This class has been invoked from another code")

    def my_func_2(self):
        print("This class has been called from the command line")

if __name__ == "__main__":
    MyClass(from_command_line = True)

像这样,如果执行来自命令行,则变量from_command_line将为真,在任何其他情况下它将为假。除非有人犯了错误。异常处理可以解决的问题。如果您有更好的方法来做到这一点,我非常想了解它。


推荐阅读