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"). 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.