Home > Software engineering >  How to import a class with composition from a module?
How to import a class with composition from a module?

Time:11-21

Assuming I have a module example.py with the following two classes. One containing the other:

#example.py
class Employee():
    def __init__(self,name):
        Self.name=name

class Company():
    def __init__(self,company,boss):
        Self.company=company
        self.boss = Employee(boss)

If I want to instantiate company in other file called work.py I go:

#work.py
from example import Company
mycompany=company('bmw','michael)

This code seems to work. Now I don't understand why because how does python know about the class Employee in the file work.py?

Would the code be "safer" in work.py if I do:

from example import Company, Employee

CodePudding user response:

work.py doesn't need to know about it. Company.__init__ has its own reference to the global scope of example where the free variable Employee is looked up.

>>> from example import Company
>>> Company.__init__.__globals__['Employee']
<class 'example.Employee'>

from example import Company creates a new global variable in work.py that is initialized using example.Company. Since Company.__init__ doesn't know or care about the global scope of work.py, there's no need to create an additional Employee global there.

  • Related