Using a parameter in a class in Python

I met this question when I studied Python on Codecademy, the code as shown below:

class Employee(object):
    def __init__(self, name):
        self.name = name
    def greet(self, other):
        print "Hello, %s" % other.name

class CEO(Employee):
    def greet(self, other):
        print "Get back to work, %s!" % other.name

ceo = CEO("Emily")
emp = Employee("Steve")
emp.greet(ceo)
ceo.greet(emp)

I was wondering what it means other.namehere?

self.name = namecan be interpreted as a member variable of the instance object self.name, which should be equal name, so we can say that selfthis is an instance, but nameits property, right?

And, doesn't the "Emily" mean the parameter otheron ceo = CEO("Emily"), and the "Steve" assigned nameto emp = Employee("Steve")? How can this be used?

+4
source share
1 answer

Class attributes

other.name name , other greet().

class Employee(object):
    def __init__(self, name):
        self.name = name
    def greet(self, other):
        print "Hello, %s" % other.name

class CEO(Employee):
    def greet(self, other):
        print "Get back to work, %s!" % other.name

ceo = CEO("Emily")
emp = Employee("Steve")

print emp.name, 'greets', ceo.name
emp.greet(ceo)
print
print ceo.name, 'greets', emp.name
ceo.greet(emp)

Steve greets Emily
Hello, Emily

Emily greets Steve
Get back to work, Steve!

()

CEO , Employee (, name), (, greet()).

:

  • "Emily" name CEO, CEO.

    ceo = CEO("Emily")
    
  • "" name Employee, emp.

    emp = Employee("Steve")
    
  • greet() other .

    emp.greet(ceo)
    

    CEO emp.greet(), emp.greet() - CEO, name of CEO.

  • greet() CEO

    ceo.greets(emp)
    

, , other .


: __init__(). __init__() , - . , .

+2

All Articles