我在 globals.py
中有一个类:
#!/usr/bin/env python
class fg():
def red(text): return f'\033[00;49;031m{text}\033[0m'
def heading(text): return red(text)
我的 testrun.py
脚本为:
#!/usr/bin/env python
from globals import fg
# Command 1:
print(fg.red("My text"))
# prints as expected
# Command 2:
print(fg.heading("My text"))
# throws the error: NameError: name 'red' is not defined
问题是如何在heading
函数中调用red
函数。
最佳答案
调用成员函数时,您必须使用 self 参数,并启动类。所以电话应该是这样的。
class fg():
def red(self, text):
return f'\033[00;49;031m{text}\033[0m'
def heading(self, text):
return self.red(text)
然后
print(fg().red("My text"))
# prints as expected
# Command 2:
print(fg().heading("My text"))
关于python - 如何在类中调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65839824/