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

2015-05-13 11:23:15 +08:00
 cc7756789
其实是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方法,把数据渲染到模版。
2715 次点击
所在节点    Python
2 条回复
cc7756789
2015-05-13 11:24:28 +08:00
url里面这样写 Index.index() 写错了 a.index()
fy
2015-05-13 14:55:28 +08:00
O.O 我记得django有直接用类的方法!翻一翻文档吧

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/190689

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX