0

Consider these three files:

base.py

class Base():
    def method(self):
        print('Base Class')

object = Base()

main.py

from base import object

def main():
    object.method()

if __name__ == '__main__':
    main()

test.py

import main
import base

class Derived(base.Base):
    def method(self):
        print('Derived Class')

base.object = Derived()

main.main()

I would expect that launching test.py will invoke the method() function of derived class but it is not.

$ python3.8 test.py
Base Class

But it works if I change the way I import object in main.py

new main.py

import base

def main():
    base.object.method()

if __name__ == '__main__':
    main()

new output:

$ python3.8 test.py
Derived Class

1 Answer 1

2

Short answer: because they are different object.

In the first case: When you import main, you are creating object, which I call it main_object. Then you are importing base, which will create base_object. Those object are not the same(you can use id to check).

In the second case: You are referencing to the same object, thus it will produce the predicted result. try the following:

base.py

from base import obj
print(f"object from main has id = {id(obj)}")
def main():
    obj.method()

if __name__ == '__main__':
    main()

main.py

from base import obj
print(f"object from main has id = {id(obj)}")
def main():
    obj.method()

if __name__ == '__main__':
    main()

test.py

import base

import main

class Derived(base.Base):
    def method(self):
        print('Derived Class')
base.obj = Derived()
print(f"base.obj in test.py has id = {id(base.obj)}")

main.main()

Also, object is a key word in python. It's better to use different name for variables for example obj.

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

1 Comment

just noticing that "object" is not a keyword, it is the name of a builtin - there is nothing in the rules of the language preventing its reuse, but common sense. Which means, indeed, its usage as variable name should be avoided, nonetheless.

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.