How do I re-initialize the base class using self.__init__
?
In the following example my goal is to inherit eComm which is a socket derived driver. This handles connect/disconnect. If it disconnects we need to reinitialize it using __init__
, however it appears to refer to the comDriver when self.__init__
is called.
How do I properly initialize the superclass to allow for this?
(else: self.__init__
in connect() is referring to comDriver, not eComm like it should)
The following is a simple case to reproduce the error in Python 3.x
class eComm():
def __init__(self):
self.s = "example object"
self.initialized = True
self.connected = False
def connect(self, IP_ADDRESS, PORT):
if self.initialized:
print(IP_ADDRESS, PORT)
else:
print("REINITIALIZING")
self.__init__()
self.connected = True
return(True)
class comDriver(eComm):
def __init__(self, IP_ADDRESS, PORT):
self.IP = IP_ADDRESS
self.PORT = PORT
super().__init__()
pass
def getTemp(self):
print("EXAMPLE FUNCTION")
return(1)
x = comDriver("192", 7)
x.connect("161", 6)
x.initialized = False
x.connect("111", 5)
IMO you're using the special method __init__
wrongly. It's meant to initialize a Python object, not anything outside that scope.
With your intention, I recommend that you create a separate initializer function, and call it from __init__
. Here's an example:
class eComm():
def __init__(self):
self.initialize_eComm()
def initialize_eComm(self):
self.s = "example object"
self.initialized = True
self.connected = False
And then you can replace self.__init__()
with self.initialize_eComm()
to avoid name conflict in subclasses.
self.__init__ in connect() is referring to comDriver, not eComm like it should
This doesn't quite hold -- self
refers to the calling object, which is comDriver
. If you want to call to the __init__
method on eComm
regardless of what classes extend it, you will have to reference in explicitly.
eComm.__init__(self)
But, the other answers and comments are right that this is not a good use of __init__
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.