基本上,这是我目前拥有的:
在script1中,我有这个:
class Student(object):
def __init__(self,name,school):
self.name = name
self.school = school
在script2中,我有这个:
class Teacher(object):
def __init__(self,name,school):
self.name = name
self.school = school
然后在script3中,定义实例并检查学校是否匹配:
student1=Student("Alex","Highschool")
teacher1=Teacher("Mary","Highschool")
if student1.school == teacher1.school:
print("yes")
但是,我想结合检查学校是否在script1或script2中匹配。这是我尝试过的:
class Teacher(object):
def __init__(self,name,school):
self.name = name
self.school = school
def _check_if_school_matches(self,Student()):
if self.school == Student.school:
print("yes")
但是我当然得到了SyntaxError
,我不能说_check_if_school_matches(self,student1)
,因为student1
尚未定义。
答案 0 :(得分:2)
您不需要在该方法的参数列表中创建Student
的新实例。将其更改为:
def _check_if_school_matches(self, student):
if self.school == student.school:
print("yes")
现在,如果您使用teacher1
实例在student1
上调用该方法,它将显示“是”
student1=Student("Alex", "Highschool")
teacher1=Teacher("Mary", "Highschool")
teacher1._check_if_school_matches(student1) # yes