Reputation:
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
Upvotes: 0
Views: 6347
Reputation: 28303
the Class Data
inherits from AccessKey
. So the class attribute products
is available to Data
, however, you need to access it through
self.products.products_field(...)
instead of products.products_field(...)
.
similarly, it should be results = self.products.get_products()
But note that, the instance attribute products is only set when the method key
is called, so you will get NameError
until the key
method is called, i.e.
data = Data()
data.key()
data.Print()
Also, in python getters and setters are discouraged, and a lot of stress is placed on code formatting guidelines. In your code the class methods should be lower case, but because print
would shadow a reserverd word, something like print_
would be preferable.
Upvotes: 0
Reputation: 431
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)
Upvotes: 2