Python2-打印对象的默认属性 [英] Python2 - printing an object's default attributes

查看:75
本文介绍了Python2-打印对象的默认属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是OOP的新手,但我试图查看对象的var。其他Stack-O答案也建议使用 object .__ dict __ vars(object)。因此,我进入Python外壳程序尝试了一个简单的示例,但是我没有注意到这些答案都显示了对象的默认属性,仅显示了新分配的属性,例如:

I'm new to OOP, but I'm trying to look at an object's vars. Other Stack-O answers have suggested using object.__dict__ or vars(object). So I went into the Python shell to try a quick example, but I noticed neither of these answers prints the object's default attributes, only newly-assigned attributes, e.g.:

>>> 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}

为什么一个变量中存在变量感觉,但没有另一个?是因为我没有显式地初始化它们还是什么?

Why are the variables present in one sense but not another? Is it because I didn't explicitly initialize them or something?

推荐答案

重要的是要理解在Python中,所有东西都是对象(包括函数,以及 class 声明本身)

It's important understanding that in Python everything is an object (including functions, and a class declaration itself)

执行此操作时:

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

您正在将 inty stringy 分配给 Class ,而不是实例。检查以下内容:

You're assigning inty and stringy to the Class, not to the instances. Check this:

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

print(Classy.__dict__)

等待... A class __ dict __ ?是的,因为 Classy 也是一个实例(类型为 classobj ,因为您使用的是旧样式类,实际上您不应该这样做...您应该从<$ c $继承c> object ,使您可以访问更多的 goodies

Wait... A class with a __dict__? Yeah, because Classy is also an instance (of type classobj, since you're using old style classes, which you shouldn't really do, by the way... You should inherit from object, which gives you access to more goodies)

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

现在,如果您创建了一个classy的 instance ,并放置了 inty 值,您将拥有:

Now, if you created an instance of classy, and put an inty value to it, you would have:

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'}

请参见 inty 在实例的 __ dict __ 中是否为5,但在类的 __ dict __ 中仍为3?这是因为现在您有两个 inty :一个附加到 classy ,是类的实例Classy 和另一个附加到类 Classy 本身的对象(又是 classobj

See the inty being 5 in the __dict__ of the instance but still being 3 in the __dict__ of the class? It's because now you have two inty: One attached to classy, an instance of the class Classy and another one attached to the class Classy itself (which is, in turn, an instance of classobj)

如果您这样做

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

您会看到:

5
whatevs

为什么?因为当您尝试在实例上获取 inty 时,Python会在 __ dict __ 中进行查找。实例。如果找不到,它将转到课程的 __ dict __ 。这就是 classy.stringy 上发生的事情。是在优雅 实例中吗?不对它在 Classy class 中吗?是的好的,返回那个......就是你看到的那个。

Why? Because when you try to get inty on the instance, Python will look for it in the __dict__ of the instance first. If it doesn't find it, it will go to the __dict__ of the class. That is what's happening on classy.stringy. Is it in the classy instance? Nopes. Is it in the Classy class? Yep! Aight, return that one... And that's the one you see.

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

Also, I mentioned that the Classy class is an object, right? And as such, you can assign it to something else like this:

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

然后您会看到 5 是附加在 Classy .__ init __ 中的,因为当您执行 What = Classy ,您将 Classy $code>分配给名为 What 的变量,并且在执行 foo = What()您实际上正在运行 Classy 的构造函数(请记住: What Classy 是同一件事)

And you'll see the 5 that was "attached" in Classy.__init__ because when you did What = Classy, you're assigning the class Classy to a variable named What, and when you do foo=What() you're actually running the constructor of Classy (remember: What and Classy are the same thing)

Python允许的另一件事(我个人不愿意'tlike,因为那样会使代码很难执行),将属性即时附加到实例:

Another thing Python allows (and that I personally don't like because then it makes code very difficult to follow) is attaching attributes to instances "on-the-fly":

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

哦,我说函数是对象吗?是的,它们是...,因此,您还可以为它们分配属性(也可以使代码变得非常混乱),但是您可以做到这一点...

Oh, and did I say that functions are objects? Yeah, they are... and as such, you can also assign attributes to them (also, something that makes code really, really confusing) but you could do it...

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-打印对象的默认属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆