Python:如何实现getattr?

2024-05-14 09:21:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我们班有一个口述,例如:

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

然后我想使用dict的键和MyClass实例来访问dict,例如:

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

我知道这应该由getattr实现,但我对Python还不熟悉,我不知道如何实现它。


Tags: 实例selfdatahereobjectinitdefmyclass
3条回答
class A(object):
  def __init__(self):
     self.data = {'a': 'v1', 'b': 'v2'}
  def __getattr__(self, attr):
     try:
       return self.data[attr]
     except:
       return "not found"


>>>a = A()
>>>print a.a
v1
>>>print a.c
not found
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

如果不需要设置属性,只需使用namedtuple 例如

>>> 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'

很晚才去参加派对,但找到了两个很好的资源来更好地解释这一点(IMHO)。

here所述,您应该使用self.__dict____getattr__中访问字段,以避免无限递归。提供的示例如下:

def __getattr__(self, attrName):
  if not self.__dict__.has_key(attrName):
     value = self.fetchAttr(attrName)    # computes the value
     self.__dict__[attrName] = value
  return self.__dict__[attrName]

注意:在第二行(上面),一个更像Python的方法是(has_key显然在Python 3中被删除了):

if attrName not in self.__dict__:

other resource解释了__getattr__只在对象中找不到属性时调用,并且hasattr如果有__getattr__的实现,则始终返回True。它提供了以下示例来演示:

class Test(object):
    def __init__(self):
        self.a = 'a'
        self.b = 'b'

    def __getattr__(self, name):
        return 123456

t = Test()
print 'object variables: %r' % t.__dict__.keys()
#=> object variables: ['a', 'b']
print t.a
#=> a
print t.b
#=> b
print t.c
#=> 123456
print getattr(t, 'd')
#=> 123456
print hasattr(t, 'x')
#=> True     

相关问题 更多 >

    热门问题