为什么在python中使用__setattr__? [英] Why to use __setattr__ in python?

查看:50
本文介绍了为什么在python中使用__setattr__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么使用 __setattr__ 而不是像 x.a=1 这样的简单引用.

I don't know for why using __setattr__ instead simple referencing like x.a=1.

我理解这个例子:

class Rectangle:
    def __init__(self):
        self.width = 0
        self.height = 0


x=Rectangle()
x.width=20
x.__setattr__('height',30)
setattr(x,'width',99)

但不明白为什么使用取决于字符串('height')的代码.

but don't get why using code depending on string ('height').

你能解释一下 __setattr__ 有什么优点吗?

Could you explain me what are advantages of __setattr__ ?

推荐答案

不是你自己调用的.时期.如果您因为事先不知道名称而需要使用字符串(在 99% 的人可能认为他们需要它的情况下,非常是个坏主意,几乎总是使用 dict 或列表更好/saner 选择),您使用内置的 setattr 函数.

You don't call it yourself. Period. If you need to use a string because you don't know the name beforehand (very bad idea in 99% of all cases where one might think they need this, nearly always a dict or list is a better/saner choice), you use the built-in setattr function.

但是,它是为您调用的 - 当您执行 ax = ... 时,它会按照 a.__setattr__('x', ...) (这可能是一种过度简化).并且一些对象重载它以允许一些诡计,例如模仿不变性.查看特殊方法"文档.

However, it is called for you - when you do a.x = ..., that's done as a.__setattr__('x', ...) (this is propably an oversimplification). And some objects overload it to allow some trickery, e.g. to emulate immutability. See the documentation of "special methods".

这篇关于为什么在python中使用__setattr__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆