[英]Python: Return doesn't work but Print works
我正在创建的库的重点是在您输入颜色名称时返回颜色的十六进制值。
上面的程序在 print 上运行良好,尽管它不会在print替换为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")
如果您使用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"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.