Using methods of a class from another in python
I'm working through 'Dive Into Python' on Google App Engine and came across this error while attempting to call one class's methods from another:
ERROR __init__.py:463] create() takes exactly 1 argument (2 given)
Traceback (most recent call last):
File "main.py", line 35, in get
dal.create("sample-data");
File "dataAccess/dal.py", line 27, in create
self.data_store.create(data_dictionary);
TypeError: create() takes exactly 1 argument (2 given)
Here's my main class:
# filename: main.py
from dataAccess.dal import DataAccess
class MySampleRequestHandler(webapp.RequestHandler):
"""Configured to be invoked for a specific GET request"""
def get(self):
dal = DataAccess();
dal.create("sample-data"); # problem area
MySampleRequestHandler.get()
tries to instantiate and invoke DataAccess
which is defined else where:
# filename: dal.py
from dataAccess.datastore import StandardDataStore
class DataAccess:
"""Class responsible for wrapping the specific data store"""
def __init__(self):
self.data_store = None;
data_store_setting = config.SETTINGS['data_store_name'];
if data_store_setting == DataStoreTypes.SOME_CONFIG:
self.data_store = StandardDataStore();
logging.info("DataAccess init completed.");
def create(self, data_dictionary):
# Trying to access the data_store attribute declared in __init__
data_store.create(data_dictionary);
I thought I could call DataAccess.create()
with 1 parameter for its argument, especially according to how Dive into Python notes about class method calls:
When defining your class methods, you must explicitly list self as the first argument for each method, including
__init__
. When you call a method of an ancestor class from within your class, you must include the self argument. But when you call your clas开发者_Go百科s method from outside, you do not specify anything for the self argument; you skip it entirely, and Python automatically adds the instance reference for you.
In self.data_store.create(data_dictionary)
, the self.data_store
refers to the object created by self.data_store = StandardDataStore()
in the __init__
method.
It looks like the create
method of a StandardDataStore
object doesn't expect an additional argument.
It should be self.data_store.create(data_dictionary);
精彩评论