Home > other >  How to call methods in a different class
How to call methods in a different class

Time:11-24

Confused on OOP in Python3:

main.py:

import ma as m1

r = m1.ma1() 
r.doit()
print(r.m1avar)
print(r.m2var)
r.m2do()

ma.py:

import mb as m2

class ma1(m2.mclass2):
    
    m1avar = 10
    
    def doit(self):
        self.logout("doit!")
        
    def logout(self, a):
        print(a " <--- this is correct")

mb.py:

class mclass2():
    
    m2var = 5;
    m1avar = 5;
    
    def doit(self):
        super().logout("m2 do it")
    
    def m2do(self):
        super().logout("child class")
    

Produces:

doit! <--- this is correct
10
5
Traceback (most recent call last):
  File "/home/alex/Desktop/rrr/m1.py", line 8, in <module>
    r.m2do()
  File "/home/alex/Desktop/rrr/mb.py", line 11, in m2do
    super().logout("child class")
AttributeError: 'super' object has no attribute 'logout'

How do I get the lowest class (mclass2) to access methods in a higher class ma1 - specifically the .logout method.

Thanks!

CodePudding user response:

Try this - mclass2 does not see it's parent class as super, just as itself. So it's self. that you need not super.

class mclass2():
    
    m2var = 5;
    m1avar = 5;
    
    def doit(self):
        super().logout("m2 do it")
    
    def m2do(self):
        self.logout("child class")

CodePudding user response:

The problem is that m2 doesnt inherit from m1. In other words, m2 doesn't even know that m1 exist.

The only thing you can do to make it work is assign a m1 object at an instance of the m2 object. I don't think this is a good practice.

  • Related