python @properties如何以及何时评估

发布于 2025-02-11 00:13:15 字数 656 浏览 1 评论 0原文

这是代码段。

class TestClass:
    def __init__(self):
        self.a = "a"
        print("calling init")

    @property
    def b(self):
        b = "b"
        print("in property")
        return b

test_obj = TestClass()
print("a = {} b = {}".format(test_obj.a,test_obj.b))

当变量 b 定义在test_obj内部的变量 b 获得其“ b”的值时,我正在尝试理解

从下面的屏幕截图中可以看到,第13行上的语句尚未评估/执行,但已经初始化了test_obj的 b 的值。通过在每一行上放置断点来调试这一点并没有帮助我了解这是如何发生的。

有人可以向我解释一下吗?

Here's a snippet of code.

class TestClass:
    def __init__(self):
        self.a = "a"
        print("calling init")

    @property
    def b(self):
        b = "b"
        print("in property")
        return b

test_obj = TestClass()
print("a = {} b = {}".format(test_obj.a,test_obj.b))

I'm trying to understand when the variable b defined inside test_obj gets its value of "b".

As you can see from the below screenshot, the statement on line 13 is yet to be evaluated/executed but already the value of b for test_obj has been initialized. Debugging this by placing a breakpoint on literally every single line didn't help me understand how this is happening.

enter image description here
Can someone please explain this to me ?

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

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

发布评论

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

评论(1

梦回梦里 2025-02-18 00:13:15

IDE更有可能向您展示test_obj.b的值是什么。为此,test_obj.b 中获取值。由于b是属性还是@property,debugger本质上只是test_obj.b您,这给了它值'b'

函数def b完全按照您从任何其他普通函数中期望的方式工作;只是调试器/IDE隐含地为您调用它。

More likely, the IDE is trying to show you what the value of test_obj.b is. For that it gets the value from test_obj.b. Since it doesn't make much of a difference whether b is an attribute or a @property, the debugger essentially just does test_obj.b for you, which gives it the value 'b'.

The function def b works exactly as you might expect from any other ordinary function; it's just that the debugger/IDE implicitly invokes it for you.

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