gpt4 book ai didi

Python2 - 打印对象的默认属性

转载 作者:行者123 更新时间:2023-11-30 22:23:34 24 4
gpt4 key购买 nike

我是 OOP 新手,但我正在尝试查看对象的变量。其他 Stack-O 答案建议使用 object.__dict__vars(object)。因此,我进入 Python shell 尝试一个快速示例,但我注意到这些答案都没有打印对象的默认属性,只打印新分配的属性,例如:

>>> class Classy():
... inty = 3
... stringy = "whatevs"
...
>>> object = Classy()
>>> object.inty
3
>>> object.__dict__
{}
>>> vars(object)
{}
>>> object.inty = 27
>>> vars(object)
{'inty': 27}
>>> object.__dict__
{'inty': 27}

为什么变量以某种意义存在而不是另一种意义?是因为我没有显式初始化它们还是什么?

最佳答案

重要的是要理解,在 Python 中一切都是对象(包括函数和 class 声明本身)

当你这样做时:

class Classy():
inty = 3
stringy = "whatevs"

您将 intystringy 分配给 Class,而不是分配给实例。检查一下:

class Classy():
inty = 3
stringy = "whatevs"

print(Classy.__dict__)

等等...带有__dict__?是的,因为 Classy 也是一个实例(classobj 类型),因为您正在使用 old style classes ,顺便说一句,您不应该这样做......您应该继承object,这使您可以访问更多好东西)

>>> print(type(Classy))
<type 'classobj'>

现在,如果您创建了一个 classy 的实例,并为其添加了一个 inty 值,您将拥有:

class Classy():
inty = 3
stringy = "whatevs"

def __init__(self):
self.inty = 5

classy = Classy()
print("__dict__ of instance: %s" % classy.__dict__)
print("__dict__ of Class: %s" % classy.__class__.__dict__)

哪些输出

__dict__ of instance: {'inty': 5}
__dict__ of Class: {'__module__': '__main__', 'inty': 3, '__doc__': None, '__init__': <function __init__ at 0x1080de410>, 'stringy': 'whatevs'}

看到实例的 __dict__ 中的 inty 为 5,但在类的 __dict__ 中仍然为 3?这是因为现在你有两个 inty:一个附加到 classy,一个类 Classy 的实例,另一个附加到类 Classy 本身(又是 classobj 的一个实例)

如果你这样做了

classy = Classy()
print(classy.inty)
print(classy.stringy)

你会看到:

5
whatevs
为什么?因为当您尝试在实例上获取 inty时,Python将首先在 实例__dict__中查找它。如果没有找到,就会去类的 __dict__。这就是 classy.stringy 上发生的情况。是在 classy 实例中吗?不。它属于 Classy class吗?是的!好吧,归还那个……那就是你看到的那个。

另外,我提到 Classy 类是一个对象,对吗?因此,您可以将其分配给其他类似的东西:

What = Classy  # No parenthesis
foo = What()
print(foo.inty)

您会在 Classy.__init__ 中看到“附加”的 5,因为当您执行 What = Classy 时,您'重新将 Classy 类分配给名为 What 的变量,当您执行 foo=What() 时,您实际上正在运行 What 的构造函数code>Classy (记住:WhatClassy 是同一件事)

Python 允许的另一件事(我个人不喜欢它,因为这样会使代码很难遵循)是“即时”将属性附加到实例:

classy = Classy()
try:
print(classy.other_thing)
except AttributeError:
print("Oh, dang!! No 'other_thing' attribute!!")
classy.other_thing = "hello"
print(classy.other_thing)

将输出

Oh, dang!! No 'other_thing' attribute!!
hello

哦,我有说过函数是对象吗?是的,它们是...因此,您也可以为它们分配属性(而且,这会使代码非常非常困惑),但您可以这样做...

def foo_function():
return None # Very dummy thing we're doing here
print("dict of foo_function=%s" % foo_function.__dict__)
foo_function.horrible_thing_to_do = "http://www.nooooooooooooooo.com/"
print("Horrible thing? %s" % foo_function.horrible_thing_to_do)

输出:

dict of foo_function={}
Horrible thing? http://www.nooooooooooooooo.com/

关于Python2 - 打印对象的默认属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030419/

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