【发布时间】:2019-02-04 16:04:32
【问题描述】:
这段代码有什么问题?
class Spam(object):
def __init__(self, a, b):
self.a = a
self.b = b
# using this to mark field "c" as deprecated. As per my understanding this gets called only for fields that do not exist.
def __getattr__(self, c):
print("Deprecated")
# using this to manipulate the value before storing
def __setattr__(self, name, value):
self.__dict__[name] = value + 1
# interceptor to allows me to define rules for whenever an attribute's value is accessed
def __getattribute__(self, name):
return self.__dict__[name]
spam = Spam(10, 20)
print(spam.a)
print(spam.b)
print(spam.c)
但是上面的代码没有打印任何东西。这里有什么问题,谁能帮我理解这个?我在https://rszalski.github.io/magicmethods/#access 中读到了这些方法
【问题讨论】:
-
提示:属性访问
self.__dict__是如何解决的?