Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting a class with the same name in Python

Tags:

python

class

I am new in Python and I am trying to create two classes with the same name in two different source files. Let’s call them "Main.py" and "Extension.py". The class is "MyClass". MyClass in Extesntion.py is derived from MyClass in file Main.py. If it works then when I create an object myclass and I import Extension in my code, then I would have more functions in comparison with file Main.py.

File Main.py

    class MyClass:
       def __init__(self):
         Initialize something

       def foo1(self, a, b):
         Do something

Then extension would be like this:

File Extensions.py

    import Main

    class MyClass(MyClass):
       def __init__(self):
         Initialize something

       def foo2(self, a, b):
         Do something

       def foo3(self, a, b):
         Do something

And then if I have code like this. I expect that I can't use foo2 and foo3.

    import Main

    myclass = MyClass()
    myclass.foo1(a, b)

And finally if I have code like this. I expect that I use all the functions.

    import Extension

    myclass = MyClass()
    myclass.foo1(a, b)
    myclass.foo2(a, b)
    myclass.foo3(a, b)
like image 974
Mohsen67 Avatar asked Apr 06 '17 14:04

Mohsen67


3 Answers

If you do

import main

you'll need to use main.MyClass to create an object from main.py.

Instead you can do

from main import MyClass

to have it available directly.

If you need two different classes with the same name, you can instead do

from main import MyClass as MainClass

and you'll have the class available under the name MainClass

like image 166
L3viathan Avatar answered Sep 21 '22 00:09

L3viathan


Unless you do from Extension import *, you'll need to specify the module in order to access the class.

import Main
import Extension
foo = Main.MyClass()
bar = Extension.MyClass()

If you don't want to have to specify the module, then the only way to avoid a name collision is to import the class under a different name like so:

from Main import MyClass as ClassA

like image 43
stelioslogothetis Avatar answered Sep 20 '22 00:09

stelioslogothetis


It's quite easy when you explicitly import the given name using the from {module} import {name} syntax.

File main.py

class MyClass:
    def __init__(self):
        pass

    def foo1(self, a, b):
        pass

File extensions.py

from main import MyClass

class MyClass(MyClass):
    def __init__(self):
        pass

    def foo2(self, a, b):
        pass

    def foo3(self, a, b):
        pass

File client_main.py

from main import MyClass

myinstance = MyClass()
myinstance.foo1(a, b)

File client_extensions.py

from extensions import MyClass

myinstance = MyClass()
myinstance.foo1(a, b)
myinstance.foo2(a, b)
myinstance.foo3(a, b)
like image 26
Łukasz Rogalski Avatar answered Sep 20 '22 00:09

Łukasz Rogalski