0

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

2 Answers 2

3

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 (i.e. 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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.