Section 38.9: 实例变量的默认值
如果变量包含不可变类型的值(如字符串),则可以像下面这样分配默认值
class Rectangle(object):
def __init__(self, width, height, color='blue'):
self.width = width
self.height = height
self.color = color
def area(self):
return self.width * self.height
# Create some instances of the class
default_rectangle = Rectangle(2, 3)
print(default_rectangle.color) # blue
red_rectangle = Rectangle(2, 3, 'red')
print(red_rectangle.color) # red

在构造函数中初始化可变对象(如列表)时需要小心谨慎。请看下面的示例:
class Rectangle2D(object):
def __init__(self, width, height, pos=[0,0], color='blue'):
self.width = width
self.height = height
self.pos = pos
self.color = color
r1 = Rectangle2D(5,3)
r2 = Rectangle2D(7,8)
r1.pos[0] = 4
r1.pos # [4, 0]
r2.pos # [4, 0] r2 的位置也发生了变化

造成这种行为的原因是,在 Python 中,缺省参数是在函数执行时绑定的,而不是在函数声明时绑定的。要获得一个不在实例间共享的缺省实例变量,应该使用这样的结构:
class Rectangle2D(object):
def __init__(self, width, height, pos=None, color='blue'):
self.width = width
self.height = height
self.pos = pos or [0, 0] # 默认值是 [0, 0]
self.color = color
r1 = Rectangle2D(5,3)
r2 = Rectangle2D(7,8)
r1.pos[0] = 4
r1.pos # [4, 0]
r2.pos # [0, 0] r2 的位置没有改变

另请参阅可变默认参数和 “最小惊奇 ”以及可变默认参数。
Section 38.10: 类和实例变量
每个实例的实例变量都是唯一的,而类变量则是所有实例共享的。
class C:
x = 2 # class variable
def __init__(self, y):
self.y = y # instance variable
C.x
# 2
C.y
# AttributeError: type object 'C' has no attribute 'y'
c1 = C(3)
c1.x
# 2
c1.y
# 3
c2 = C(4)
c2.x
# 2
c2.y
# 4

类变量可以在该类的实例中被访问,但赋值给类属性会创建一个实例变量,该实例变量会对类变量产生影子影响
c2.x = 4
c2.x
# 4
C.x
# 2

请注意,从实例中修改类变量可能会导致一些意想不到的后果。
class D:
x = []
def __init__(self, item):
self.x.append(item) # note that this is not an assignment!
d1 = D(1)
d2 = D(2)
d1.x
# [1, 2]
d2.x
# [1, 2]
D.x
# [1, 2]

Section 38.11: 类的构成
类组成允许对象之间存在明确的关系。在这个例子中,人们生活在属于国家的城市中。通过组合,人们可以访问居住在自己国家的所有人数:
class Country(object):
def __init__(self):
self.cities=[]
def addCity(self,city):
self.cities.append(city)
class City(object):
def __init__(self, numPeople):
self.people = []
self.numPeople = numPeople
def addPerson(self, person):
self.people.append(person)
def join_country(self,country):
self.country = country
country.addCity(self)
for i in range(self.numPeople):
Person(i).join_city(self)
class Person(object):
def __init__(self, ID):
self.ID=ID
def join_city(self, city):
self.city = city
city.addPerson(self)
def people_in_my_country(self):
x= sum([len(c.people) for c in self.city.country.cities])
return x
US=Country()
NYC=City(10).join_country(US)
SF=City(5).join_country(US)
print(US.cities[0].people[0].people_in_my_country())
# 15

Section 38.12: 列出所有类成员
dir() 函数可用于获取类的成员列表:
dir(Class)
例如
dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

通常只查找 “非魔法 ”成员。这可以通过一个简单的理解来实现,即列出名称不是以 __ 开头的成员:
>>> [m for m in dir(list) if not m.startswith('__')]
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse','sort']

警告:
类可以定义一个 __dir__() 方法。如果该方法存在,调用 dir() 将调用 __dir__(),否则 Python 将尝试创建该类的成员列表。这意味着 dir 函数可能会产生意想不到的结果。引述两段 Python 官方文档中的重要内容:
如果对象没有提供
dir(),函数会尽力从对象的dict属性(如果定义了)和类型对象中收集信息。如果对象有自定义的getattr(),生成的列表不一定完整,而且可能不准确。注意:由于
dir()主要是为了方便在交互式提示符下使用,因此它会尽量 提供一组有趣的名称,而不是提供一组严格或一致定义的名称。例如,当参数是一个类时,元类属性不在结果列表中。
Section 38.13: 单例类
单例是一种将类的实例化限制为一个实例/对象的模式。有关 python 单例设计模式的更多信息,请参见此处。
class Singleton:
def __new__(cls):
try:
it = cls.__it__
except AttributeError:
it = cls.__it__ = object.__new__(cls)
return it
def __repr__(self):
return '<{}>'.format(self.__class__.__name__.upper())
def __eq__(self, other):
return other is self
另一种方法是装饰你的类。根据本答案中的示例创建一个单例类:
class Singleton:
"""
A non-thread-safe helper class to ease implementing singletons.
This should be used as a decorator -- not a metaclass -- to the
class that should be a singleton.
The decorated class can define one `__init__` function that
takes only the `self` argument. Other than that, there are
no restrictions that apply to the decorated class.
To get the singleton instance, use the `Instance` method. Trying
to use `__call__` will result in a `TypeError` being raised.
Limitations: The decorated class cannot be inherited from.
"""
def __init__(self, decorated):
self._decorated = decorated
def Instance(self):
"""
Returns the singleton instance. Upon its first call, it creates a
new instance of the decorated class and calls its `__init__` method.
On all subsequent calls, the already created instance is returned.
"""
try:
return self._instance
except AttributeError:
self._instance = self._decorated()
return self._instance
def __call__(self):
raise TypeError('Singletons must be accessed through `Instance()`.')
def __instancecheck__(self, inst):
return isinstance(inst, self._decorated)
您可以使用实例方法
@Singleton
class Single:
def __init__(self):
self.name=None
self.val=0
def getName(self):
print(self.name)
x=Single.Instance()
y=Single.Instance()
x.name='I\'m single'
x.getName() # outputs I'm single
y.getName() # outputs I'm single
Section 38.14: 描述符和点式查找
描述符是作为类的属性(通常)的对象,具有 __get__、__set__ 或 __delete__中的任意一种特殊方法。
数据描述符具有__set__或__delete__中的任何一种方法。
这些方法可以控制实例上的点查询,并用于实现函数、staticmethod、classmethod 和 property。点式查找(例如,类 Foo 的实例 foo 查找属性 bar - 即 foo.bar)使用以下算法:
- 在类
Foo中查找bar。如果存在,并且是数据描述符,则使用该数据描述符。这就是property如何控制对实例中数据的访问,而且实例不能覆盖这一点。如果数据描述符不存在,那么就会在实例__dict__中查找。这就是为什么我们可以用点查找覆盖或阻止从实例中调用的方法。如果bar存在于实例中,则使用它。如果不存在,我们就在Foo类中查找bar。如果是描述符,则使用描述符协议。这就是函数(此处指非绑定方法)、“classmethod”和 “staticmethod”的 “实现 ”方式。否则,它将简单地返回对象,或者出现AttributeError错误。