V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
cc7756789
V2EX  ›  Python

python 一个子类集成了一个父类,如何直接以 子类.method() 方法调用子类的函数

  •  
  •   cc7756789 · 2015-05-13 11:23:15 +08:00 · 2707 次点击
    这是一个创建于 3298 天前的主题,其中的信息可能已经有所发展或是发生改变。
    其实是Django中我想用类的方法来重写 views.py

    这是urls.py
    ---------------------------------------------
    from django.conf.urls import patterns, url
    from .views import Index

    urlpatterns = patterns('',
    url(r'^$', Index.index(), name="index" ),)


    这是views.py:
    ------------------------------------------------------
    class BaseMixin(object):
    def __init__(self):
    self.latest_article_list = Article.objects.order_by('-date')[:15]
    self.context = {'latest_article_list':self.latest_article_list}
    self.python_list = Article.objects.filter(category='python')

    class Index(BaseMixin):
    def __init__(self):
    super(Index,self).__init__(self)
    def index(self, request):
    return render(request, 'home/index.html', self.context)

    def python(self, request):
    return render(request, 'home/python.html', {'python_list':self.python_list})


    但是输出TypeError
    unbound method index() must be called with Index instance as first argument (got nothing instead)


    然后我在urls.py里面实例化了
    a=Index()
    url里面这样写 Index.index()

    但是错误说需要传入2个参数,我也是初学,只能用函数的方法来不厌其烦地往views中写。
    请问这两个情况该怎么样解决
    我想直接 Index.index() 然后可以成功执行Index类的index方法,把数据渲染到模版。
    2 条回复
    cc7756789
        1
    cc7756789  
    OP
       2015-05-13 11:24:28 +08:00
    url里面这样写 Index.index() 写错了 a.index()
    fy
        2
    fy  
       2015-05-13 14:55:28 +08:00
    O.O 我记得django有直接用类的方法!翻一翻文档吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1136 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 19:04 · PVG 03:04 · LAX 12:04 · JFK 15:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.