gpt4 book ai didi

python - 如何在Python中确定对象的值

转载 作者:太空宇宙 更新时间:2023-11-03 20:31:58 24 4
gpt4 key购买 nike

来自文档

Every object has an identity, a type and a value.

  • type(obj) 返回对象的类型
  • id(obj) 返回对象的 id

有什么东西可以返回它的值吗?诸如用户定义对象之类的对象的值代表什么?

最佳答案

要真正查看对象值/属性,您应该使用 magic method __dict__

这是一个简单的例子:

class My:
def __init__(self, x):
self.x = x
self.pow2_x = x ** 2

a = My(10)
# print is not helpful as you can see
print(a)
# output: <__main__.My object at 0x7fa5c842db00>

print(a.__dict__.values())
# output: dict_values([10, 100])

或者您可以使用:

print(a.__dict__.items())
# output: dict_items([('x', 10), ('pow2_x', 100)])

关于python - 如何在Python中确定对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57443045/

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