Python:返回不起作用,但Print工作

时间:2018-02-26 15:39:42

标签: python function dictionary switch-statement return

我正在创建的库的目的是在输入颜色名称时返回颜色的十六进制值。

上述程序可以正常使用打印,但只要打印替换为返回,它就不会返回值。 但是返回值的整个点已经消失,因为它不能与其他程序一起使用。 return(“#F2F3F4”)不起作用

是的我没有括号我尝试过它并没有任何区别。 希望你能弄明白这个问题。提前谢谢!

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")

1 个答案:

答案 0 :(得分:2)

如果您使用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。相反,您可以将其作为返回值的函数,并在调用函数时打印该值,使其更具可重用性。此外,不是将颜色名称映射到函数,而是每个都返回值,您可以直接将名称映射到值。

def colour_const(name):
    colour_codes = {
        "Anti-flash white": "#F2F3F4", 
        "Antique white": "#FAEBD7",
        "Beige": "#F5F5DC",
        "Blond" : "#FAF0BE"
    }
    return colour_codes.get(name, "unknown color")

print(colour_const("Anti-flash white"))
相关问题