无聊之人--除了技术,还是技术,你懂得
分类: Python/Ruby
2011-08-06 23:06:25
5.8. Introducing Class Attributes
类属性介绍
You already know about data attributes, which are variables owned by a specific instance of a class. Python also supports class attributes, which are variables owned by the class itself.
你早已经知道数据属性,他是只对类的某个实例可用的变量。Python同样支持类属性,属于类本身的属性。
Example 5.17. Introducing Class Attributes
例5.17 类属性简介
MP3FileInfo is the class itself,
not any particular instance of the class. MP3FileInfo 是类本身,不是任何类的实例 tagDataMap is a class attribute:
literally, an attribute of the class. It is available before creating any
instances of the class. tagDataMap 是一个类属性,字面意思是一个类的属性。在创建任意类实例之前该变量就可用。 Class attributes are available both
through direct reference to the class and through any instance of the class. 类属性不仅对任意类的直接引用可用,对类的实例引用同样可用。 In Java, both static variables
(called class attributes in Python) and instance variables (called data
attributes in Python) are defined immediately after the class definition
(one with the static keyword, one without). In Python, only
class attributes can be defined here; data attributes are defined in
the __init__ method. 在java中所有的静态变量(在Python中北称为类属性)和实例变量((在Python称之为数据属性)都是直接在类定义的后面定义(一个含有关键字static,另一个没有)。在Python中,只有类属性可以定义在类定义的后面;数据属性定义在__init__方法中。
Class attributes can be used as class-level constants (which is how you use them in MP3FileInfo), but they are not really constants. You can also change them.
类属性可以用作类级别常量(这是你在MP3Fileinfo中的用法),但是他们实际上不是常量,你同样可以改变它们。
|
|
|
There are no constants in Python. Everything can be changed if you try hard enough. This fits with one of the core principles of Python: bad behavior should be discouraged but not banned. If you really want to change the value of None, you can do it, but don't come running to me when your code is impossible to debug. 在Python中没有常量,所有的对象都可以被改变,如果你努力尝试的话。这对应了Python的一个核心原则:坏行为不应该被鼓励,但是不应该被禁止。如果你确实想修改None的值,你同样可以,但是当代码变得不能调试的时候不要来找我! |
|
Example 5.18. Modifying Class Attributes
例5.18 修改类属性
count is a class attribute of
the counter class. Count是cunter类的一个类属性。 __class__ is a built-in attribute
of every class instance (of every class). It is a reference to the class
that self is an instance of (in this case,
the counter class) __class__是所有类实例的一个内置属性。它是对该类的一个引用,self是该类的一个实例(在本例中,是cunter类。. Because count is a class
attribute, it is available through direct reference to the class, before you have created any instances
of the class. 因为count是类属性,在你创建任意类实例之前,对类的直接引用而言,类属性也是可用的, Creating an instance of the class calls
the __init__ method, which increments the class
attribute count by 1. This affects the class itself, not just
the newly created instance. 创建类的实例,调用__init__方法,这这使得类属性count增加1.这影响了类本身,不仅仅是刚刚创建的类实例。 Creating a second instance will
increment the class attribute count again. Notice how the class
attribute is shared by the class and all instances of the class. 再次创建一个新实例将使得类属性count继续增加1.注意一下类属性是如何在类以及类实例之间的共享。