是用户定义的类可变的 [英] are user defined classes mutable
问题描述
说我想为 car
, tractor
和 boat
。所有这些类都有一个
engine
的实例,我想跟踪单个列表中的所有引擎。如果我理解正确如果电机对象是可变的,我可以将其作为 car
的属性,并且在列表中的同一个实例。
Say I want to create a class for car
, tractor
and boat
. All these classes have an instance of engine
and I want to keep track of all the engines in a single list. If I understand correctly if the motor object is mutable i can store it as an attribute of car
and also the same instance in a list.
我无法跟踪任何关于用户定义的类是否可变的固定信息,并且如果有一个选择来选择定义它们,任何人都可以发光? p>
I cant track down any solid info on whether user defined classes are mutable and if there is a choice to choose when you define them, can anybody shed some light?
推荐答案
用户类被认为是可变的。 Python不具有(绝对)私有属性,所以你可以随时通过到达内部来改变类。
User classes are considered mutable. Python doesn't have (absolutely) private attributes, so you can always change a class by reaching into the internals.
要使用你的类作为一个键在 dict
或将它们存储在 set
中,您可以定义 .__ hash __()
方法和 .__ eq __()
方法,确保您的类是不可变的。您通常设计类API,以便在这种情况下不会改变内部状态。
For using your class as a key in a dict
or storing them in a set
, you can define a .__hash__()
method and a .__eq__()
method, making a promise that your class is immutable. You generally design your class API to not mutate the internal state after creation in such cases.
例如,如果您的引擎由其ID唯一定义,作为你的哈希的基础:
For example, if your engines are uniquely defined by their id, you can use that as the basis of your hash:
class Engine(object):
def __init__(self, id):
self.id = id
def __hash__(self):
return hash(self.id)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.id == other.id
return NotImplemented
现在您可以在集合中使用类Engine的实例:
Now you can use instances of class Engine in sets:
>>> eng1 = Engine(1)
>>> eng2 = Engine(2)
>>> eng1 == eng2
False
>>> eng1 == eng1
True
>>> eng1 == Engine(1)
True
>>> engines = set([eng1, eng2])
>>> engines
set([<__main__.Engine object at 0x105ebef10>, <__main__.Engine object at 0x105ebef90>])
>>> engines.add(Engine(1))
>>> engines
set([<__main__.Engine object at 0x105ebef10>, <__main__.Engine object at 0x105ebef90>])
在上面的示例中,我向该集合添加了另一个 Engine(1)
实例,但它被识别为已存在,更改
In the above sample I add another Engine(1)
instance to the set, but it is recognized as already present and the set didn't change.
请注意,对于列表, .__ eq __()
实现是重要的;列表不关心对象是否是可变的,但是使用 .__ eq __()
方法就可以测试给定的引擎是否已经在列表中: / p>
Note that as far as lists are concerned, the .__eq__()
implementation is the important one; lists don't care if an object is mutable or not, but with the .__eq__()
method in place you can test if a given engine is already in a list:
>>> Engine(1) in [eng1, eng2]
True
这篇关于是用户定义的类可变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!