在python中创建类和定义连接有什么问题

use*_*366 0 python redis

我在python中创建了一个类,并__init__在类方法中调用变量.很少有init变量会出错.

以下是班级:

class MyRedisClass(object):

  def __init__(self):
    self.DEFAULT_PAGE_SIZE = 10
    # the line below gives an error - global name 'pool' is not defined
    # if the below line is commented, I can get the value of DEFAULT_PAGE_SIZE inside the some_function
    self.pool = redis.ConnectionPool(host='XXX.XXX.XX.XX', port=XXXX, db=0) 
    self.redis_connection = redis.Redis(connection_pool=pool)

  def some_function(self, some_data):
    print self.DEFAULT_PAGE_SIZE
    pipeline = self.redis_connection.pipeline()
    it = iter(some_data)
    for member, score in zip(it, it):
        pipeline.zadd(leaderboard_name, member, score)
    pipeline.execute()
Run Code Online (Sandbox Code Playgroud)

在终端我创建一个类的实例如下 -

mklass = MyRedisClass()
mklass.some_function(['a', 1])
Run Code Online (Sandbox Code Playgroud)

正如指出我得到一个错误 - global name 'pool' is not defined

上述类声明有什么问题?

为什么我在声明池时会收到NameError?

为了更好的类定义,我是否需要做一些superclassmethod

Ter*_*ryA 5

您访问poolself.pool,而不是仅仅池:

self.redis_connection = redis.Redis(connection_pool=self.pool)
Run Code Online (Sandbox Code Playgroud)