class Classroom:
classroom_list=None
@staticmethod
def search_classroom(class_room):
global classroom_list
for classroom in classroom_list:
if(classroom==class_room):
return "Found"
else:
return -1
c=Classroom()
Classroom.classroom_list=['w','e','d','o']
Classroom.search_classroom('w')
答案 0 :(得分:2)
我认为您正在使事情变得过于复杂,我认为这样会容易得多。
class Classroom:
def __init__(self, classroom_list):
self.classroom_list = classroom_list
def search_classroom(self, class_room):
return "Found" if class_room in self.classroom_list else -1
c = Classroom(['w','e','d','o'])
c.search_classroom('g')
答案 1 :(得分:1)
执行global classroom_list
时,您的函数正在最外面的范围内寻找classroom_list
:
@staticmethod
def search_classroom(class_room):
global classroom_list # here
for classroom in classroom_list:
..那里没有定义教室列表。
相反,请使用@classmethod
装饰器执行所需的操作,因为它将为您提供对当前类的引用作为其第一个参数:
@classmethod
def search_classroom(cls):
for classroom in cls.classroom_list:
然后,您可以在类中引用的属性上进行迭代,因为您已经在外部为其分配了值。
但是,您可能需要重写此代码,以使用对象和实例属性而不是类属性。