gpt4 book ai didi

Python 对象 - 避免创建名称未知的属性

转载 作者:太空狗 更新时间:2023-10-29 17:27:55 24 4
gpt4 key购买 nike

希望避免这样的情况:

>>> class Point:
x = 0
y = 0
>>> a = Point()
>>> a.X = 4 #whoops, typo creates new attribute capital x

我创建了以下对象用作父类(super class):

class StrictObject(object):
def __setattr__(self, item, value):
if item in dir(self):
object.__setattr__(self, item, value)
else:
raise AttributeError("Attribute " + item + " does not exist.")

虽然这似乎可行,但 python documentation says of dir() :

Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

有没有更好的方法来检查对象是否具有属性?

最佳答案

更好的方法。

最常见的方式是“我们都是同意的成年人”。这意味着,您不进行任何检查,而将其留给用户。您所做的任何检查都会降低代码在使用中的灵 active 。

但是如果你真的想这样做,有__slots__默认情况下在 Python 3.x 中,对于 Python 2.x 中的新式类:

By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.

The default can be overridden by defining __slots__ in a new-style class definition. The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.

Without a __dict__ variable, instances cannot be assigned new variables not listed in the __slots__ definition. Attempts to assign to an unlisted variable name raises AttributeError. If dynamic assignment of new variables is desired, then add '__dict__' to the sequence of strings in the __slots__ declaration.

例如:

class Point(object):
__slots__ = ("x", "y")

point = Point()
point.x = 5 # OK
point.y = 1 # OK
point.X = 4 # AttributeError is raised

最后,检查对象是否具有特定属性的正确方法不是使用dir,而是使用内置函数hasattr(object, name)。 .

关于Python 对象 - 避免创建名称未知的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9646015/

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