gpt4 book ai didi

Python:如何实现 __getattr__()?

转载 作者:IT老高 更新时间:2023-10-28 21:47:01 25 4
gpt4 key购买 nike

我的类(class)有一个字典,例如:

class MyClass(object):
def __init__(self):
self.data = {'a': 'v1', 'b': 'v2'}

那我想用 dict 的 key 和 MyClass 实例来访问 dict,例如:

ob = MyClass()
v = ob.a # Here I expect ob.a returns 'v1'

我知道这应该由 __getattr__ 实现,但我是 Python 新手,我不完全知道如何实现它。

最佳答案

class MyClass(object):

def __init__(self):
self.data = {'a': 'v1', 'b': 'v2'}

def __getattr__(self, attr):
return self.data[attr]

>>> ob = MyClass()
>>> v = ob.a
>>> v
'v1'

在实现 __setattr__ 时要小心,您需要进行一些修改:

class MyClass(object):

def __init__(self):
# prevents infinite recursion from self.data = {'a': 'v1', 'b': 'v2'}
# as now we have __setattr__, which will call __getattr__ when the line
# self.data[k] tries to access self.data, won't find it in the instance
# dictionary and return self.data[k] will in turn call __getattr__
# for the same reason and so on.... so we manually set data initially
super(MyClass, self).__setattr__('data', {'a': 'v1', 'b': 'v2'})

def __setattr__(self, k, v):
self.data[k] = v

def __getattr__(self, k):
# we don't need a special call to super here because getattr is only
# called when an attribute is NOT found in the instance's dictionary
try:
return self.data[k]
except KeyError:
raise AttributeError

>>> ob = MyClass()
>>> ob.c = 1
>>> ob.c
1

如果您不需要设置属性,只需使用命名元组例如。

>>> from collections import namedtuple
>>> MyClass = namedtuple("MyClass", ["a", "b"])
>>> ob = MyClass(a=1, b=2)
>>> ob.a
1

如果你想要默认参数,你可以围绕它编写一个包装类:

class MyClass(namedtuple("MyClass", ["a", "b"])):

def __new__(cls, a="v1", b="v2"):
return super(MyClass, cls).__new__(cls, a, b)

或者它作为一个函数看起来更好:

def MyClass(a="v1", b="v2", cls=namedtuple("MyClass", ["a", "b"])):
return cls(a, b)

>>> ob = MyClass()
>>> ob.a
'v1'

关于Python:如何实现 __getattr__()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16237659/

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