当用户输入名称(例如" Jim")作为我"测试"的实例的参数时class,def find
函数被调用并且for循环遍历dict匹配" Jim"中的所有名称。如果def find
找到了关键词" Jim"在dict中,它应该打印出相应的值。但是,当我运行代码时,它只是说"无"。我需要更改哪些内容,以便调用def find
会导致打印语句'工作'
class Test(object):
def __init__(self, x=0): # error in (def find)?
self.x = x
c = None # error while looping in the for loop?
users = {
'John': 1,
'Jim': 2,
'Bob': 3
}
def find(self, x): # The user is supposed to type in the name "x"
for self.c in self.users: # it goes through the dictionary
if x == self.users[self.c]: # If x is equal to key it prints worked
print('worked')
else:
pass
beta = Test()
print(beta.find('Jim'))
答案 0 :(得分:2)
@ nk001,
我认为这有点像你想要的:
class Test(object):
def __init__(self, x=0):
self.x = x # <-- indent the __init__ statements
users = { # <-- users = {
'John': 1, # KEY: VALUE,
'Jim': 2, # KEY: VALUE,
'Bob': 3 # KEY: VALUE,
} # }
def find(self, x): # <-- The user passes the "x" argument
for i in self.users: # <-- Now it goes through the dictionary
if x == i: # <-- If ARGV('x') == KEY
return 'worked' # <-- Then RETURN 'worked'
else:
pass
beta = Test()
print(beta.find("Jim"), beta.users["Jim"])
有几种不同的方法可以获得'工作'的消息并打印相应的值,这只是一个示例来演示访问dict [KEY]以获得VALUE。
另外,我只是假设你的意思是if / else块,而不是for / else?缩进对于Python来说至关重要。此外,您的原始脚本返回None,因为for循环中没有明确的return
- 因此,当函数在函数完成时在打印语句print(beta.find('Jim'))
中调用它时,它不返回任何内容(“无”) )。希望有所帮助!
答案 1 :(得分:1)
我写了一个有用的代码:
class Test(object):
users = {
'John': 1,
'Jim': 2,
'Bob': 3
}
def __init__(self, x=0): # So I don't get an error in (def find)
self.x = x
def find(self, x): # The user is suppose to type in the name "x"
for name in Test.users.keys(): # it goes through the dictionary
if x == name: # If x is equal to key it prints worked
print('worked', self.users[name])
else:
pass
beta = Test()
beta.find('Jim')
self.c
。users
是一个类变量,您需要Test.users
访问它。Test.users.keys()
print(beta.find('Jim'))
将打印find
的返回值。但是,您不会手动返回值,输出中会得到None
。