python - 如何在类中调用函数?

标签 python function class

我在 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/

相关文章:

python - 如何随机化 if/elif 语句的顺序?

c++ - *& 在函数参数中是什么意思

java - 如何在实现 Parcelable 的类中使用 transient 变量?

php - 扩展供应商使用的 Laravel 类

python - 如何将小时添加到 Pandas 数据框列

python - Qt Designer和PyQt程序中verticalLayout的大小不同

python - 在 Pycharm 2016.3 中安装 pip

javascript - 我的代码中的回调似乎不起作用,并且在没有应用回调函数的情况下返回结果

c++ - 有条件地为变量分配一个类

python - 什么是嵌套循环,如何在下面的示例中使用它?