在 codecademy 学习 Python 时遇到的问题,创建了两个类Employee
和CEO
:
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) # Hello, Emily
ceo.greet(emp) # Get back to work, Steve!
这里为什么会有other.name
这种用法,是什么意思?
self.name = name
理解为当前对象的成员变量name
赋值为name
,是不是说self
就是实例,name
就是它的一个属性?
那么other.name
是什么意思呢?
Huh? It's very simple. 1. There is a name attribute (member variable) in the other parameter. 2.self points to the object itself instantiated by the class.
Other is an instance object parameter. This instance object has the attribute name. If the object you pass in is not an instance of CEO or Employee, an exception AttributeError will be reported.