Giant Blob
Giant Blob

Reputation: 71

python class inheritance def __init bit?

I am using Python 3 with PyQt4 and :

I have a first class :

class MainWindow(QtGui.QWidget):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.initUI()

with this function in it :

def Fn_GetSpnBitsValue(self):
        print (self.SpnBits.value())
        self.BitNumber =self.SpnBits.value()
        print(self.BitNumber)
        return self.BitNumber

as you can see I return the value of one of my spinners created in this class Now I want to access this variable "self.BitNumber" from another class. In other language I would very simply write myValue = MainWindow.self.BitNumber but it seems it wont be as easy in python, so I have look at class inheritance so my second class inherit of my first one...

I would be very tempted to write like this ... :

class BitsWindow(QtGui.QWidget, MainWindow):   
    def __init__(self):
        super(BitsWindow, self).__init__()
        self.initUI2()

Which makes perfect sens to me, I tell my second class "look you inherit from this class so everything she know, you know it as well" but I then get this message error :

 class BitsWindow(QtGui.QWidget, MainWindow):
TypeError: Cannot create a consistent method resolution
order (MRO) for bases QWidget, MainWindow

Which don't really make any sens to me actually. By looking further on the web I have think understand the key is in that bit :

def __init__(self):
        super(BitsWindow, self).__init__()
        self.initUI2()

But I really struggle understanding the concept, I am not sure what this is doing despite numerous tutorials and forum answers. (Maybe, probably, didn't find the good ones.)

Any help would be much appreciated;

Many Thanks !

Upvotes: 0

Views: 164

Answers (1)

sebastian
sebastian

Reputation: 9696

The issue is, that BitsWindow inherits from QWidget and MainWindow, even though MainWindow already is a QWidget.

This spoils python's strategy to determine which e.g. which __init__ method it should use, the one of QWidget or the one from MainWindow:

The MainWindow definition tells python to take MainWindow before the ones of QWidget. When you define BitsWindow(QWidget, MainWindow) you give QWidget precedence over MainWindow. These two strategies collide and that's why you get the error.

So, simply change your class definition from

class BitsWindow(QtGui.QWidget, MainWindow):
...

to

class BitsWindow(MainWindow):
...

FWIW, you could also keep the redundant QWidget inheritance if you really want to, if you change the order:

class BitsWindow(MainWindow, QWidget):
    ...

should also work.

EDIT:

Inheritance may however not actually be what you want. You can get that result be simply accessing it from an instance of MainWindow:

main = MainWindow()
myValue = main.Fn_GetSpnBitsValue()

or

main.Fn_GetSpnBitsValue()
myValue = main.BitNumber

Upvotes: 1

Related Questions