【问题标题】:Importing Model / Lib Class and calling from controller导入模型/库类并从控制器调用
【发布时间】:2009-08-12 20:07:23
【问题描述】:

我是 python 和 pylons 的新手,虽然在 PHP 方面有经验。

我正在尝试编写一个模型类,它将充当我对我的数据库 (couchdb) 的数据访问。我的问题很简单

我的模型看起来像这样,名为 models/BlogModel.py

from couchdb import *

class BlogModel:

    def getTitles(self):
        # code to get titles here

    def saveTitle(self):
       # code to save title here

我的控制器叫做 controllers/main.py

import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to

from billion.lib.base import BaseController, render

log = logging.getLogger(__name__)

from billion.model import BlogModel

class MainController(BaseController):

    def index(self):
        return render('/main.mako') 

在我的索引操作中,如何访问 BlogModel 中的 getTitles() 方法?

我试过了

x = BlogModel()
x.getTitles()

但我明白了 TypeError: 'module' 对象不可调用

还有 BlogModel.getTitles() 结果 AttributeError:“模块”对象没有属性“getTitles”

这取决于我包含课程的方式吗?有人能告诉我最好的方法吗?

谢谢

【问题讨论】:

    标签: python model-view-controller pylons


    【解决方案1】:
    x = BlogModel.BlogModel()
    

    或者,更详细地说:

    导入后,您的命名空间中有一个名为“BlogModel”的对象。该对象是 BlogModel 模块。 (模块名称来自文件名。)在该模块内部,有一个名为“BlogModel”的类对象,这就是您所追求的。 (类名来源于你写的源代码。)

    代替:

    from billion.model import BlogModel
    

    你可以使用:

    from billion.model.BlogModel import BlogModel
    

    那么你的

    x = BlogModel()
    

    会起作用的。

    【讨论】:

    • 在 python 中,习惯上使用小写字母命名模块,以避免这种混淆: from billion.model.blogmodel import BlogModel
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多