user1629366
user1629366

Reputation: 2001

What is wrong with creating a class and defining a connection in python

I have created a class in python, and calling the __init__ variables in class methods. Few of the init variables give error.

Following is the class :

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

In the terminal I create an instance of class as follows -

mklass = MyRedisClass()
mklass.some_function(['a', 1])

as pointed out I get an error - global name 'pool' is not defined

What is wrong with the above class declaration?

Why am I getting NameError, at the place when I am declaring pool?

For a better class definition, do I need to do some super or classmethod?

Upvotes: 0

Views: 87

Answers (1)

TerryA
TerryA

Reputation: 59974

You access pool as self.pool instead of just pool:

self.redis_connection = redis.Redis(connection_pool=self.pool)

Upvotes: 5

Related Questions