python-3.x - 如果从命令行调用一个类而不是在代码中调用一个类,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__":
部分。
解决方案
我想使用它的上下文是让主类的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
将为真,在任何其他情况下它将为假。除非有人犯了错误。异常处理可以解决的问题。如果您有更好的方法来做到这一点,我非常想了解它。
推荐阅读
- c++ - 当实现完全在我的 .HPP 文件中时,编译器正在寻找 .CPP 文件
- javascript - 使 HTML 元素继承另一个元素的变换
- android - 如何在 Kotlin 的 Fragment 中获取非 null 和 runOnUIThread() 的活动?
- reactjs - React:如何编辑 HTML 片段的 DOM
- jquery - 带有特殊字符的 jQuery 平滑滚动
- r - 如何在 R 中交叉加入
- java - 在 Spring 中使用 ClientHttpRequestInterceptor 时如何中止请求?
- sql - SQLite UPDATE WHERE 查询
- python - 在 Python 中使用 OpenGL 渲染纹理不是
- c# - Url.Action() 在 ASP.NET Core 3.0 中返回 null