在 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
是什么意思呢?
え? とてもシンプルです。 1. もう一方のパラメータにname属性(メンバ変数)があります。 2.self は、クラスによってインスタンス化されたオブジェクト自体を指します。
Other はインスタンス オブジェクト パラメータです。このインスタンス オブジェクトには属性名があります。渡したオブジェクトが CEO または Employee のインスタンスではない場合、例外 AttributeError が報告されます。