Python乱砍只读属性

时间:2016-06-21 10:17:43

标签: python

我正在使用一些具有一些只读属性的第三方代码。 我显然想要改变它们。

我尝试使用del但我不断获得:AttributeError: can't delete attribute

这是我的代码:

for page in suggested_pages:
    url = page.url + '?source=smart_404'
    full_url = page.full_url + '?source=smart_404'

    del page.url
    del page.full_url

    page.url = url
    page.full_url = full_url

编辑人员一直在询问属性的代码

@property
def full_url(self):
    """Return the full URL (including protocol / domain) to this page, or None if it is not routable"""
    url_parts = self.get_url_parts()

    if url_parts is None:
        # page is not routable
        return

    site_id, root_url, page_path = url_parts

    return root_url + page_path

@property
def url(self):
    """
    Return the 'most appropriate' URL for referring to this page from the pages we serve,
    within the Wagtail backend and actual website templates;
    this is the local URL (starting with '/') if we're only running a single site
    (i.e. we know that whatever the current page is being served from, this link will be on the
    same domain), and the full URL (with domain) if not.
    Return None if the page is not routable.
    """
    url_parts = self.get_url_parts()

    if url_parts is None:
        # page is not routable
        return

    site_id, root_url, page_path = url_parts

    if len(Site.get_site_root_paths()) == 1:
        # we're only running a single site, so a local URL is sufficient
        return page_path
    else:
        return root_url + page_path

代码来自Wagtail CMS

1 个答案:

答案 0 :(得分:0)

在Python中,只读属性通常通过property函数实现。

示例:

class A(object):
    def __init__(self, val):
        self._val = val
    @property
    def val(self):
        return self._val

这意味着只读属性不是对象的属性,而是类本身的特殊属性。

希望您可以轻松地将一个二传手添加到一个属性中:

def setval(self, val):
    self._val = val
A.val = A.val.setter(setval)
a = A(5)
a.val
-> 5
a.val = 6
-> 6

或者您也可以完全取代该属性。对于您的课程,您可以这样做(我使用clazz作为您要更改的课程的名称)

clazz.orig_url = url
def set_url(self, url):
    self._url = url
clazz.url = property((lambda self: self._url), seturl)

然后你可以这样做:

page.url = url
print(page.url)

主要的警告是你必须修改拥有的类而不仅仅是实例。