Now what can we do with instance objects? The only operations understood by instance objects are attribute references. There are two kinds of valid attribute names.
现在我们可以用实例对象作什么?实例对象唯一可用的操作就是属性引用。有两种有效的属性名。
The first I'll call data attributes. These correspond to
``instance variables'' in Smalltalk, and to ``data members'' in
C++. Data attributes need not be declared; like local variables,
they spring into existence when they are first assigned to. For
example, if x
is the instance of MyClass created above,
the following piece of code will print the value 16
, without
leaving a trace:
第一种称作数据属性。这相当于 Smalltalk 中的“实例变量”或 C++
中的“数据成员”。和局部变量一样,数据属性不需要声明,第一次使用时它们就会生成。例如,如果
x
是前面创建的 MyClass 实例,下面这段代码会打印出
16
而不会有任何多余的残留:
x.counter = 1 while x.counter < 10: x.counter = x.counter * 2 print x.counter del x.counter
The second kind of attribute references understood by instance objects are methods. A method is a function that ``belongs to'' an object. (In Python, the term method is not unique to class instances: other object types can have methods as well. For example, list objects have methods called append, insert, remove, sort, and so on. However, below, we'll use the term method exclusively to mean methods of class instance objects, unless explicitly stated otherwise.)
第二种为实例对象所接受的引用属性是方法。方法是属于一个对象的函数。(在 Python 中,方法不止是类实例所独有:其它类型的对象也可有方法。例如,链表对象有 append,insert,remove,sort 等等方法。然而,在这里,除非特别说明,我们提到的方法特指类方法)
Valid method names of an instance object depend on its class. By
definition, all attributes of a class that are (user-defined) function
objects define corresponding methods of its instances. So in our
example, x.f
is a valid method reference, since
MyClass.f
is a function, but x.i
is not, since
MyClass.i
is not. But x.f
is not the same thing as
MyClass.f
-- it is a method object, not
a function object.
实例对象的有效名称依赖于它的类。按照定义,类中所有(用户定义)的函数对象对应它的实例中的方法。所以在我们的例子中,
x.f
是一个有效的方法引用,因为 MyClass.f
是一个函数。但 x.i
不是,因为 MyClass.i
是不是函数。不过 x.f
和 MyClass.f
不同--它是一个
方法对象,不是一个函数对象。