Python:Return不起作用,但Print有效

2024-09-27 00:21:51 发布

您现在位置:Python中文网/ 问答频道 /正文

当你输入颜色的十六进制值时。在

上面的程序可以很好地使用print,尽管一旦printreturn替换,它不会立即返回值。 但是返回一个值的全部意义都消失了,因为它不能与其他程序一起使用。 return(“#f2f4f4”)不起作用

是的,我试过不加括号的方法,没有任何区别。 希望你能解决这个问题。提前谢谢你!在

class ColourConst():
    def __init__(self, colour):
        col = ""
        #Shades of White
        def Anti_flash_white():
             print("#F2F3F4")

        def Antique_white():
            print("#FAEBD7")

        def Beige():
            print("#F5F5DC")

        def Blond():
            print("#FAF0BE")

        ColourCon = {
        #Shades of White
        "Anti-flash white": Anti_flash_white, 
        "Antique white": Antique_white,
        "Beige": Beige,
        "Blond" : Blond
        }
        myfunc = ColourCon[colour]
        myfunc()

ColourConst("Anti-flash white")

Tags: of程序returndefflashprintwhitecolour
1条回答
网友
1楼 · 发布于 2024-09-27 00:21:51

如果您使用return,它会返回一个值,但是除非您也使用print,否则它不会打印它。在

class ColourConst():
    def __init__(self, colour):
        def Anti_flash_white():
            return "#F2F3F4" # return here
        def Antique_white():
            return "#FAEBD7" # and here
        def Beige():
            return "#F5F5DC" # and here
        def Blond():
            return "#FAF0BE" # you get the point...
        ColourCon = {
            "Anti-flash white": Anti_flash_white, 
            "Antique white": Antique_white,
            "Beige": Beige,
            "Blond" : Blond
        }
        myfunc = ColourCon[colour]
        print(myfunc()) # add print here

ColourConst("Anti-flash white")

这样做很可怕。首先,这是一个类的构造函数,根据定义,它只能返回该类新创建的实例self。相反,您只需使它成为一个返回值的函数,并在调用函数时打印该值,使其更具可重用性。另外,您可以直接将名称映射到值,而不是将颜色名称映射到函数中,每个函数都返回值。在

^{pr2}$

相关问题 更多 >

    热门问题