Class objects support two kinds of operations: attribute references and instantiation.
类对象支持两种操作:属性引用和实例化。
Attribute references use the standard syntax used for all
attribute references in Python: obj.name
. Valid attribute
names are all the names that were in the class's namespace when the
class object was created. So, if the class definition looked like
this:
属性引用使用和Python中所有的属性引用一样的标准语法:
obj.name
。类对象创建后,类命名空间中所有的命名都是有效属性名。所以如果类定义是这样:
class MyClass: "A simple example class" i = 12345 def f(self): return 'hello world'
then MyClass.i
and MyClass.f
are valid attribute
references, returning an integer and a method object, respectively.
Class attributes can also be assigned to, so you can change the value
of MyClass.i
by assignment. __doc__ is also a valid
attribute, returning the docstring belonging to the class: "A
simple example class"
.
那么 MyClass.i
和 MyClass.f
是有效的属性引用,分别返回一个整数和一个方法对象。也可以对类属性赋值,你可以通过给
MyClass.i
赋值来修改它。 __doc__
也是一个有效的属性,返回类的文档字符串: "A simple example
class"
。
Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example (assuming the above class):
类的实例化使用函数符号。只要将类对象看作是一个返回新的类实例的无参数函数即可。例如(假设沿用前面的类):
x = MyClass()
creates a new instance of the class and assigns this object to
the local variable x
.
以上创建了一个新的类实例并将该对象赋给局部变量 x
。
The instantiation operation (``calling'' a class object) creates an empty object. Many classes like to create objects in a known initial state. Therefore a class may define a special method named __init__(), like this:
这个实例化操作(“调用”一个类对象)来创建一个空的对象。很多类都倾向于将对象创建为有初始状态的。因此类可能会定义一个名为 __init__() 的特殊方法,像下面这样:
def __init__(self): self.data = []
When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance. So in this example, a new, initialized instance can be obtained by:
类定义了 __init__() 方法的话,类的实例化操作会自动为新创建的类实例调用 __init__() 方法。所以在下例中,可以这样创建一个新的实例:
x = MyClass()
Of course, the __init__() method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to __init__(). For example,
当然,出于弹性的需要, __init__() 方法可以有参数。事实上,参数通过 __init__() 传递到类的实例化操作上。例如:
>>> class Complex: ... def __init__(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5)