gpt4 book ai didi

Python 3 用户定义的不可变类对象

转载 作者:行者123 更新时间:2023-12-04 12:08:25 24 4
gpt4 key购买 nike

根据我的理解,Python 用户定义的类实例默认是不可变的。不可变对象(immutable对象)不会改变它们的哈希值,它们可以用作字典键和集合元素。

我有以下代码片段。

class Person(object):
def __init__(self, name, age):
self.name=name
self.age=age

现在,我将实例化 Person 类并创建一个对象并打印其哈希值。
jane = Person('Jane', 29)
print(jane.__hash__())
-9223371933914849101

现在,我将改变 jane 对象并打印其哈希值。
jane.age = 33
print(jane.__hash__())
-9223371933914849101

我的问题是即使 jane 对象是可变的,为什么它的哈希值没有改变?

此外,我可以使用可变 jane 对象作为字典键和设置元素。

最佳答案

要定义具有不可变实例的类,您可以执行以下操作:

class Person:
"""Immutable person class"""

# Using __slots__ reduces memory usage.
# If __slots__ doesn't include __dict__, new attributes cannot be added.
# This is not always desirable, e.g. it you want to subclass Person.
__slots__ = ('name', 'age')

def __init__(self, name, age):
"""Create a Person instance.

Arguments:
name (str): Name of the person.
age: Age of the person.
"""
# Parameter validation. This shows how to do this,
# but you don't always want to be this inflexibe.
if not isinstance(name, str):
raise ValueError("'name' must be a string")
# Use super to set around __setattr__ definition
super(Person, self).__setattr__('name', name)
super(Person, self).__setattr__('age', int(age))

def __setattr__(self, name, value):
"""Prevent modification of attributes."""
raise AttributeError('Persons cannot be modified')

def __repr__(self):
"""Create a string representation of the Person.
You should always have at least __repr__ or __str__
for interactive use.
"""
template = "<Person(name='{}', age={})>"
return template.format(self.name, self.age)

一个测试:
In [2]: test = Person('S. Eggs', '42')

In [3]: str(test)
Out[3]: "<Person(name='S. Eggs', age=42)>"

In [4]: test.name
Out[4]: 'S. Eggs'

In [5]: test.age
Out[5]: 42

In [6]: test.name = 'foo'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-1d0482a5f50c> in <module>()
----> 1 test.name = 'foo'

<ipython-input-1-efe979350b7b> in __setattr__(self, name, value)
24 def __setattr__(self, name, value):
25 """Prevent modification of attributes."""
---> 26 raise AttributeError('Persons cannot be modified')
27
28 def __repr__(self):

AttributeError: Persons cannot be modified

关于Python 3 用户定义的不可变类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42452953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com