[英]Double class definitions in python
I just realized the following works. 我刚刚意识到以下作品。 How come it works? 如何运作? What are the details of this? 这有什么细节? What happens if the class definitions differ? 如果类定义不同会怎样?
class A(object):
pass
class A(object):
pass
The second definition overrides the first definition. 第二个定义将覆盖第一个定义。 It's not different from simple variables: 它与简单变量没有什么不同:
>>> i = 2
>>> i = 3
>>> print(i)
3
Same holds true for functions: you just re-define it. 函数也是如此:您只需重新定义它。
>>> def f(): return 1
...
>>> def f(): return 2
...
>>> f()
2
Python doesn't enforce the uniqueness of the object names (ie doesn't crash with "...already defined"). Python不会强制对象名称的唯一性(即不会因“ ...已经定义”而崩溃)。 It also doesn't care about the internals: first class definition might have different methods from the second class definition. 它也不在乎内部:第一类定义可能具有与第二类定义不同的方法。 The order is the only thing that matters here. 顺序是这里唯一重要的事情。
The second definition gets overriden. 第二个定义被覆盖。
$ cat test.py
class A(object):
def __str__(self):
return 'first A'
class A(object):
def __str__(self):
return 'second A'
a1 = A()
print(a1)
$ python test.py
second A
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.