Reputation: 71
I met this question as I learned Python on Codecademy, code as 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 does other.name
mean here?
The self.name = name
could be interpreted as a instance object's member variable self.name
be set equal to name
, so we can say that self
is a instance and name
is its property, right?
And, isn't the "Emily" assigned to the parameter other
by ceo = CEO("Emily")
and the "Steve" assigned to the name
by emp = Employee("Steve")
? How could it be used like that?
Upvotes: 4
Views: 104
Reputation: 10758
other.name
is the name
attribute of any class instance that is passed as an argument to the other
parameter of the greet()
method.
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
inherits everything defined by Employee
(like the name
attribute), but can alter things (like altering the greet()
method).
Here is what is going on:
"Emily" is assign to the name
attribute of the CEO
class when an instance of that class is created as ceo
.†
ceo = CEO("Emily")
"Steve" is assigned to the name
attribute of the Employee
class when an instance of that class is created as emp
.†
emp = Employee("Steve")
In the an instance's greet()
call, the whole other class instance is passed to it thru the other
parameter of that method.
emp.greet(ceo)
This passes all of ceo
into emp.greet()
, so that emp.greet()
can access something from ceo
, in this case, the name
of ceo
.
The greet()
call is repeated for the ceo
instance
ceo.greets(emp)
I hope this is clear, read about and play with some other examples of classes.
† : this is what the __init__()
method is for. __init__()
can take any argument, assign anything, or run any code. It is called whenever an instance of the class is created.
Upvotes: 2