python @properties如何以及何时评估
这是代码段。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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 fromtest_obj.b
. Since it doesn't make much of a difference whetherb
is an attribute or a@property
, the debugger essentially just doestest_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.