谁可以调用 __get__、__set__ 和 __del__?

发布于 2024-08-15 08:06:44 字数 478 浏览 3 评论 0原文

这是我的代码。我不知道为什么它不起作用。

class a:
    def __get__(self):
        return 'xxx'
    def aa(self):
        print 'aaaa'

b=a()
print b.get('aa')

请尝试用代码回答,因为我的英语不是很好。谢谢。

class HideX(object):
    def __init__(self, x):
        self.x = x

    def get_x(self):
        return self.__x

    def set_x(self, x):
        self.__x = x+10

    x = property(get_x, set_x)

inst = HideX(20)
print inst.x
inst.x = 30
print inst.x

This is my code. I don't know why it doesn't work.

class a:
    def __get__(self):
        return 'xxx'
    def aa(self):
        print 'aaaa'

b=a()
print b.get('aa')

Please try to answer in code, because my English is not very good. Thank you.

class HideX(object):
    def __init__(self, x):
        self.x = x

    def get_x(self):
        return self.__x

    def set_x(self, x):
        self.__x = x+10

    x = property(get_x, set_x)

inst = HideX(20)
print inst.x
inst.x = 30
print inst.x

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

黯淡〆 2024-08-22 08:06:44

您正在调用 obj.get,但 class A 中没有 get 函数,因此出现错误,
__get__ 重命名为 get 或者如果您偶然尝试使用描述符,请执行以下操作

class A(object):
    def __get__(self, obj, klass):
        print "__get__", obj, klass
        return 'xxx'

class X(object):
    a = A()

x=X()
print x.a

You are calling obj.get, but there is no get function in class A, hence error,
either rename __get__ to get or if you by chance are trying to use descriptors do something like this

class A(object):
    def __get__(self, obj, klass):
        print "__get__", obj, klass
        return 'xxx'

class X(object):
    a = A()

x=X()
print x.a
卖梦商人 2024-08-22 08:06:44

我认为您应该在尝试使用 描述符 之前阅读更多内容。

I think you should read a bit more on Descriptors before you try to use them.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文