In this code:
(在此代码中:)
class A(object):
def __init__(self):
self.x = 'Hello'
def method_a(self, foo):
print self.x + ' ' + foo
... the self
variable represents the instance of the object itself.
(... self
变量表示对象本身的实例。)
Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; (大多数面向对象的语言将此作为隐藏参数传递给在对象上定义的方法。)
Python does not. (Python没有。)
You have to declare it explicitly. (您必须明确声明它。)
When you create an instance of the A
class and call its methods, it will be passed automatically, as in ... (当创建A
类的实例并调用其方法时,它将自动传递,如...)
a = A() # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument
The __init__
method is roughly what represents a constructor in Python.
(__init__
方法大致代表Python中的构造函数。)
When you call A()
Python creates an object for you, and passes it as the first parameter to the __init__
method. (调用A()
Python会为您创建一个对象,并将其作为第一个参数传递给__init__
方法。)
Any additional parameters (eg, A(24, 'Hello')
) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them. (任何其他参数(例如A(24, 'Hello')
)也将作为参数传递-在这种情况下,将引发引发异常,因为构造函数不需要它们。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…