gpt4 book ai didi

python - self.arg = arg 和 self.__dict__ ['arg' ] = arg 在 Python 中的区别

转载 作者:太空狗 更新时间:2023-10-30 00:47:38 27 4
gpt4 key购买 nike

当我定义类时,我总是去

Class A(object):
def __init__(self, arg):
self.arg = arg
def print_arg(self):
print(self.arg)

a = A('hello')

print a.arg

'hello'

但是我在第 133 行和第 134 行发现的 的 https://github.com/Pylons/webob/blob/master/src/webob/request.py让我思考我在 A 类中所做的与以下内容之间的区别是什么:

Class B(object):
def __init__(self, arg):
self.__dict__['arg'] = arg
def print_arg(self):
print(self.arg)

b = B('goodbye')

print b.arg

'goodbye'

最佳答案

有几个主要的影响:

  1. 使用 self.__dict__ 添加属性规避 __setattr__,这可能会因某些您可能希望在某些地方避免的行为而过载。

    In [15]: class Test(object):
    ...: def __init__(self, a, b):
    ...: self.a = a
    ...: self.__dict__['b'] = b
    ...: def __setattr__(self, name, value):
    ...: print('Setting attribute "{}" to {}'.format(name, value))
    ...: super(Test, self).__setattr__(name, value)
    ...:

    In [16]: t = Test(1, 2)
    Setting attribute "a" to 1

    您可以看到没有为属性 b 打印任何内容。

  2. 在某些情况下不够灵活

    In [9]: class WithSlots(object):
    ...: __slots__ = ('a',)
    ...: def __init__(self, a):
    ...: self.__dict__['a'] = a
    ...:

    In [10]: instance = WithSlots(1)
    ---------------------------------------------------------------------------
    AttributeError Traceback (most recent call last)
    <ipython-input-10-c717fcc835a7> in <module>()
    ----> 1 instance = WithSlots(1)

    <ipython-input-9-2d23b670e0fc> in __init__(self, a)
    2 __slots__ = ('a',)
    3 def __init__(self, a):
    ----> 4 self.__dict__['a'] = a
    5

    AttributeError: 'WithSlots' object has no attribute '__dict__'

    In [11]: class WithSlots(object):
    ...: __slots__ = ('a',)
    ...: def __init__(self, a):
    ...: self.a = a
    ...:
    ...:

    In [12]: instance = WithSlots(1) # -> works fine
  3. 您不能在类定义之外执行此操作。

关于python - self.arg = arg 和 self.__dict__ ['arg' ] = arg 在 Python 中的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48025092/

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