python字典的值如何打印
推测你的意图,做了一些修改:
class Chinese:
def __int__(self):
self._number = None
def set_number(self,value):
if value >=1 and value <=5:
self._number = value
else: raise ValueError("Number not recognized")
def chinese(self):
number2chinese = {1:"一",2:"二",3:"三",4:"四",5:"五"}
return number2chinese[self._number]
def set_chinese(self,value):
chinese2number = {"一":1,"二":2,"三":3,"四":4,"五":5}
if value in chinese2number:
self._number = chinese2number[value]
else:
raise ValueError("Chinese numeral not recognized")
a = Chinese()
a.set_number(3)
print(a._number)
print(a.chinese())
b = Chinese()
b.set_chinese("五")
print(b._number)
print(b.chinese())
运行环境Python 2.7.16, 结果:
2019-04-28 · 知道合伙人IT服务行家
class Chinese:
def __int__(self):
self._number = None
def number(self,value):
if value >=1 and value <=5:
self._number = value
return self._number
else:
raise ValueError("Number not recognized")
def chinese(self,value):
chinese2number = {"一":1,"二":2,"三":3,"四":4,"五":5,1:"一",2:"二",3:"三",4:"四",5:"五"}
if value in chinese2number.keys():
return chinese2number[value]
else:
raise ValueError("Chinese numeral not recognized")
a = Chinese()
print(a.number(1))
print(a.chinese(1))
print(a.chinese('一'))
b = Chinese()
print(b.number(5))
print(a.chinese(5))
print(b.chinese('五'))
判断字典键要用dict.keys(),根据你的代码我改了一点,看能不能达到你的要求