0

Essentially, this is what I currently have:

In script1 I have this:

class Student(object):
    def __init__(self,name,school):
        self.name = name
        self.school = school

In script2 I have this:

class Teacher(object):
    def __init__(self,name,school):
        self.name = name
        self.school = school

And in script3, I define the instances and check if the schools match:

student1=Student("Alex","Highschool")
teacher1=Teacher("Mary","Highschool")

if student1.school == teacher1.school:
    print("yes")

However I would like to incorporate checking if the schools matched in either script1 or script2. This is what I have tried:

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")

But of course I get a SyntaxError, and I can't say _check_if_school_matches(self,student1) because student1 is not defined yet.

martineau
  • 119,623
  • 25
  • 170
  • 301
Radwa Sharaf
  • 159
  • 14

1 Answers1

2

You don't need to create a new instance of Student in that method's argument list. Change that to:

def _check_if_school_matches(self, student):
    if self.school == student.school:
        print("yes")

So now if you call that method on teacher1 with the student1 instance, it prints "yes"

student1=Student("Alex", "Highschool")
teacher1=Teacher("Mary", "Highschool")

teacher1._check_if_school_matches(student1) # yes

What is duck typing?

slider
  • 12,810
  • 1
  • 26
  • 42