我在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()
在终端中,我创建了一个类实例,如下所示 -
mklass = MyRedisClass()
mklass.some_function(['a', 1])
指出我收到错误 - global name 'pool' is not defined
上述类声明有什么问题?
为什么我在声明池时会收到NameError?
为了更好的课程定义,我是否需要执行一些super
或classmethod
?
答案 0 :(得分:5)
您可以pool
访问self.pool
而不只是访问池:
self.redis_connection = redis.Redis(connection_pool=self.pool)