How to acces class variables outside class in python
Question: I am new to python and this is my first program in python i want to know how
to access class variables outside class.I have a code which throws some error

    
    
    from xxxxxxx import Products
    
    class AccessKey(object):
        def key(self):
            self.products = Products(
               api_key = "xxxxxxxxxxxxxxxxxxxxxx",
               api_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
            )
    
    class Data(AccessKey):
        def Print(self):
            products.products_field( "search", "Samsung Galaxy" )
            results = products.get_products()
            print "Results of query:\n", results
    
    data = Data()
    data.Print()
    

The above program throws following error

    
    
    Traceback (most recent call last):
      File "framework.py", line 10, in <module>
        class Data(AccessKey):
      File "framework.py", line 13, in Data
        results = products.get_products()
    NameError: name 'products' is not defined
    


Answer: First of all, you need to call the products field as **self.products.** (etc)

It looks like you don't necessarily instantiate "products" before you call it.
If you want to make sure it's instantiated, then you need to have products be
set in the constructor of the parent class (AccessKey)

A simplified example would be:

    
    
    class A (object):
        def __init__ (self):
            self.x = 1
    
    class B (A):
        def get (self):
            return self.x
    
    b = B ()
    print (b.get ())
    

Basically, you would have to add the following constructor to your first class

    
    
    class AccessKey(object):
        def __init__(self):
            self.products = Products (X, Y) # or whatever you want to initialize it to
        # the rest of your code below
    

Or, you can be even better and create a set_product function:

    
    
    # inside of the parent class
        def set_product (self, X, Y):
            try:
                self.products.product_field (X, Y)
            except NameError:
                self.products = Product (X, Y)
    

