gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:28:19 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com