为类变量设置属性

时间:2019-01-09 11:53:19

标签: python getattr setattr

我试图在建立到另一个类中的变量的连接后,基本上设置一个类属性redisconnection对象。我使用setattr设置变量。当我尝试访问该变量时,该值为null。

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")

在确定我哪里出错时需要帮助。请问classmethod合适吗?如果访问对象的方式错误,也要提出建议。

0 个答案:

没有答案
相关问题