访问实例属性和类属性之间的区别 [英] Difference between accessing an instance attribute and a class attribute

查看:91
本文介绍了访问实例属性和类属性之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python类

I have a Python class

class pytest:
    i = 34
    def func(self):
        return "hello world"

当我访问pytest.i时,我得到34.我也可以用另一种方式做到这一点:

When I access pytest.i, I get 34. I can also do this another way:

a = pytest()
a.i

这也给出了34.

如果我尝试访问(不存在的)pytest.j,我会得到

If I try to access the (non-existing) pytest.j, I get

Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
pytest.j
AttributeError: class pytest has no attribute 'j'

当我尝试a.j时,错误是

Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
a.j
AttributeError: pytest instance has no attribute 'j'

所以我的问题是:在这两种情况下到底发生了什么?有什么区别?

So my question is: What exactly happens in the two cases and what is the difference?

推荐答案

不,这是两个不同的东西.

No, these are two different things.

在Python中,一切都是对象.类是对象,函数是对象,实例是对象.由于所有事物都是对象,因此所有事物的行为都类似.在您的情况下,您将创建一个名称为"pytest"的类实例(==类型为"Class"的对象).该对象具有两个属性:ifuc. i是"Integer"或"Number"的实例,fuc是"Function"的实例.

In Python, everything is an object. Classes are objects, functions are objects and instances are objects. Since everything is an object, everything behaves in a similar way. In your case, you create a class instance (== an object with the type "Class") with the name "pytest". That object has two attributes: i and fuc. i is an instance of "Integer" or "Number", fuc is an instance of "Function".

当您使用"pytest.j"时,您告诉python查找对象pytest,当您拥有它时,查找i". "pytest"是一个类实例,但这没关系.

When you use "pytest.j", you tell python "look up the object pytest and when you have it, look up i". "pytest" is a class instance but that doesn't matter.

当您创建"pytest"的实例(==类型为"pytest"的对象)时,您将拥有一个具有默认值"的对象.在您的情况下,apytest的实例,这意味着将在pytest中搜索a中找不到的所有内容.

When you create an instance of "pytest" (== an object with the type "pytest"), then you have an object which has "defaults". In your case, a is an instance of pytest which means that anything that can't be found in a will be searched in pytest, next.

所以a.j的意思是:查找a.如果不存在,也请查找pytest".但是j不存在,Python现在必须为您提供有意义的错误消息.可以说"pytest类没有属性'j'".这是正确的,但毫无意义:您必须弄清楚自己试图通过a访问j.这会令人困惑. Guido不会拥有的.

So a.j means: "Look in a. When it's not there, also look in pytest". But j doesn't exist and Python now has to give you a meaningful error message. It could say "class pytest has no attribute 'j'". This would be correct but meaningless: You would have to figure out yourself that you tried to access j via a. It would be confusing. Guido won't have that.

因此,python使用了不同的错误消息.由于它并不总是具有实例名称(a),因此设计人员决定改用类型,因此您将获得"pytest实例...".

Therefore, python uses a different error message. Since it does not always have the name of the instance (a), the designers decided to use the type instead, so you get "pytest instance...".

这篇关于访问实例属性和类属性之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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