哪个类拥有方法和属性
假设我们有这样的代码:
class C(CC):
a = 1
b = 2
def __init__(self):
self.x = None
self.y = 1
如何在 Python 中快速找到属性或方法的定义位置?如果它属于祖先类或者它是类C的方法。您可以看到属性 a, b, x, y
。他们一定属于C类吗?或者他们可能来自祖先阶级?什么时候将类型分配给变量?
为什么不直接使用
class C(CC):
a = 1
b = 2
x = None
y = 1
谢谢
Let's say we have this code:
class C(CC):
a = 1
b = 2
def __init__(self):
self.x = None
self.y = 1
How can I quickly find out in Python where is the attribute or method defined? If it belongs to ancestor class or if it's the method of class C. You can see attributes a, b, x, y
. Must they belong to class C? or can they be from ancestor classes? When does the type is assigned to the variable?
Why not rather use
class C(CC):
a = 1
b = 2
x = None
y = 1
thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第一个示例中,
a
和b
是 C 类对象的属性。 (想想“静态”属性。)x
和y
是 C 实例的属性。 (因此,是常规实例属性。)在第二个示例中,所有四个属性都是 C 的属性,而不是其实例的属性。
在 Python 中,您无法“声明”特定类定义的属性,这意味着一开始就没有要继承的属性定义。 (或多或少,但我不会通过引入 __slots__ 来混淆视听)。您可以通过搜索“def method_name(”来查找方法定义,并且方法定义是继承的,就像大多数 OO 语言一样。
令人困惑的是,您可以通过类的实例访问类属性,然后如果您分配为该属性添加新值,创建一个新的实例属性:
这确实允许您通过使用类属性为实例属性提供默认值,但我不认为这是很常见的事情 - 我喜欢使用
__init__()
参数。In the first example,
a
andb
are attributes of the C class object. (Think "static" attributes.) Andx
andy
are attributes of C instances. (So, regular instance attributes.)In the second example, all four are attributes of C, not of its instances.
In Python, you can't "declare" attributes as defined by a specific class, which means there are no attribute definitions to inherit to begin with. (More or less, but I'm not going to muddle the waters by introducing
__slots__
). You can find method definitions by searching for "def method_name(", and method definitions are inherited as in most OO languages.Confusingly, you can access class attributes through instances of a class, then if you assign a new value to that attribute, a new instance attribute is created:
Which does let you give instance attribute default values by using class attributes. I don't believe this is a very common thing to do though – I favour using default values to
__init__()
arguments.为什么不使用
这不同一件事。它有四个类级属性,由类
C
的所有对象共享。这一点,是不同的。它有两个由
C
类的所有对象共享的类级属性和两个对于C
类的每个对象都是唯一的实例变量。您的两个代码示例非常不同。它们无法相提并论。
为了回答你的另一个问题,我们使用GREP和其他工具来搜索源代码。这很容易。
Why not rather use
This is not the same thing. This has four class-level attributes which are shared by all objects of class
C
.This, is different. It has two class-level attributes shared by all objects of class
C
and two instance variables which are unique to each object of classC
.Your two code samples are very different. They cannot be compared.
To answer your other question, we use GREP and other tools to search the source. It's easy.