【发布时间】:2019-07-11 15:54:46
【问题描述】:
我正在尝试调用其他类的方法,并为被调用类提供当前类的引用以及其他一些参数。但不知何故,它将作为参数给出的自我作为被调用类的自我。
让我告诉你:
import os, sys
from wsPart import wsPart
class thermo(wsPart):
functional = False ## see line 8
file = '/sys/bus/w1/devices/28-00000833e8ff/w1_slave'
def __init__(self, name, logger):
super().__init__(name, logger)
functional = True
def read(self):
fileobject = open(self.file)
filecontent = fileobject.read()
fileobject.close()
self.logger.writeLog(self,"Completed Meassurement") ##Problem on this line
return filecontent
所以我调用类logger 和方法writeLog。提供参数消息和类 thermo (self) 的引用。
import datetime
from wsPart import wsPart
class logger():
logfile = "/var/log/wheaterstation.log"
name = "Logger"
def writeLog(self, sender, message):
conn = open(self.logfile, "w")
now = str(datetime.datetime.now().isoformat())
conn.write("[" + now + "]" + " (" + sender.getName() + "): " + message + "\n") ##Problem on this line
conn.close()
如您所见,我输入了参数self,因为它是属于一个类的方法,sender 应该是对在 thermo 类中作为 self 传递的类 thermo 的引用。最后还有 message,它也在 thermo 类中通过。
但这只是给了我错误:
Traceback (most recent call last):
File "scrLib/wsControl.py", line 61, in <module>
controller = controller()
File "scrLib/wsControl.py", line 22, in __init__
self.thermo = thermo("Thermometer", logger)
File "/home/joco/git/wheaterstation/scrLib/thermo.py", line 10, in __init__
super().__init__(name, logger)
File "/home/joco/git/wheaterstation/scrLib/wsPart.py", line 8, in __init__
self.logger.writeLog(self, "created")
TypeError: writeLog() missing 1 required positional argument: 'message'
因此,在 thermo 类中传递的 self 参数似乎被解释为 logger 类的 self,这让一切都混淆了。
你们能帮帮我吗?
完整代码+附加cmets可查看Here
编辑:
logger 和 thermo 类都在文件 wsPart.py 中初始化:
class controller():
name = ""
logger = None
thermo = None
dbConnector = None
def __init__(self):
##THis created the controller and all the other objects
self.name = "Controller"
##Create Objects
self.logger = logger()
self.logger.writeLog(self,"logger created") ##This line Works
self.thermo = thermo("Thermometer", logger)
self.dbConnector = dbConnector("DBConnector",logger)
【问题讨论】:
-
您确定
self.logger是logger的实例 吗?你能edit 展示你是如何初始化它的吗? (注意:我不会访问完整代码的链接) -
@Jean-FrançoisFabre 我添加了两者都被初始化的部分。
标签: python python-3.x python-2.7 oop reference