classvariab的setattribute

2024-06-25 23:14:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试设置一个class属性,一旦与另一个类中的变量建立了连接,就可以重新连接对象。我使用setattr来设置变量。当我尝试访问变量时,值为空。你知道吗

import importlib
import json
import sys
import time
import traceback
from twisted.python import log
import txredisapi
from settings import gcl_decorator_init
from twisted.internet import reactor

REDIS_HOST = 'localhost'
REDIS_PORT = 6379

class TestLogger(object):

    connectionObj = None

    @classmethod
    def log(cls, data):
        connObject = getattr(TestLogger, "connectionObj")
        print("connObject is : ",connObject)
        cls.connectionObj.publish("TestChannel","DataNew")

class TestServiceProtocol(txredisapi.SubscriberProtocol):

    def connectionMade(self):
        conn = txredisapi.lazyConnection(host=REDIS_HOST, port=REDIS_PORT)
        print("connected. and alive.",conn)
        setattr(TestLogger, "connectionObj", conn)
        print('value of CollectorService.connection : ',getattr(TestLogger,"connectionObj"))

    def messageReceived(self, pattern, channel, message):
        pass

    def connectionLost(self, reason):
        print("lost connection to the redis server, Reason : ", reason)

class TestServiceFactory(txredisapi.SubscriberFactory):
    maxDelay = 120
    continueTrying = True
    protocol = TestServiceProtocol

class TestService(object):
    manager = None
    connection = None

    @staticmethod
    def initialize():
        try:
            svc = TestServiceFactory()
            return svc
        except Exception as ex:
            log.msg("Exception {}".format(traceback.format_exc()))
            log.msg("Failed to initialize service {}".format(ex))
            time.sleep(5)
            raise ex

if __name__ == '__main__':
    svc = TestService.initialize()
    reactor.connectTCP(REDIS_HOST, REDIS_PORT, svc)
    reactor.run()

下面是测试程序

from untitled import TestLogger

if __name__ == "__main__":
    testLogger = TestLogger()
    print("connection from object : ",getattr(testLogger,"connectionObj"))
    TestLogger.log("Data")

需要帮助确定我哪里出错了。分类方法合适吗?如果访问对象的方法错误,也抛出建议。你知道吗


Tags: fromimportredisloghostportdefconnection