栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python:如何实现__getattr __()?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python:如何实现__getattr __()?

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.c1

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

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

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

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'


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610992.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号