无法在python中获取当前网址 [英] can't able to get current url in python
本文介绍了无法在python中获取当前网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经创建了一个类和方法,如下所示。我需要获取当前页面的网址。但是调用get_full_path()时出错。
I have created a class and method as like below. I need to get current page url. But am getting error while calling get_full_path().
class A(object):
def get_user(request):
current_url = request.get_full_path()
return current_url
class B(A):
b = A()
b.get_user()
print b.current_url
Traceback Error:
AttributeError: 'A' object has no attribute 'get_full_path'
我犯了什么错误?
推荐答案
此代码由于某些误解而无法正常工作:
This code cannot work because has some misconceptions:
- 您应该将
请求
传递给get_user
- 首先
get_user
的参数应该是self
,它指向 A 实例。 - 对象无法返回值(您在 A
class
返回current_url >)。 - 在此示例中不必使用类继承。
- You should pass
request
toget_user
- First argument of
get_user
should beself
which points to A instance. - Object cannot return value (you have
return current_url
in Aclass
). - It is not necessary to use class inheritance in this example.
您的代码应如下所示:
class A(object):
current_url = None
def get_user(self, request):
self.current_url = request.get_full_path()
b = A()
b.get_user(request)
print b.current_url
或者如果您要将完整路径传递给 class A $ c $的构造函数c>,并且出于任何原因在继承的类B中使用它:
Or if you want to pass full path to constructor of class A
, and for whatever reason use it in inherited class B:
class A(object):
def __init__(self, current_url):
self.url = current_url
def get_path(self):
return self.current_url
class B(A):
# whatever you need here
pass
b = B(request.get_full_path())
print b.get_path() # prints current path
这篇关于无法在python中获取当前网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文