Python中某些属性的自定义AttributeErrors

问题描述

@H_502_1@我已经发布了以下问答,尽管不确定是否有更好的模式可以遵循。如果是,请发表评论或回答!

我想知道当有人尝试访问我创建的class中的某个属性/方法时是否可以提供自定义AttributeError。除了不鼓励用户以某种方式访问​​属性外,我还希望该错误提供一种替代方法

我的示例是代表目录的简单class

class Folder:
    def __init__(self,parent=None):
        self._parent = parent

    def get_parent(self):
        return self._parent

e = Folder()
f = Folder(e) 

直接通过属性更改文件夹的父目录可能会导致问题(例如,您还需要告诉父文件夹其子目录已更改)。我不鼓励使用前导下划线“保护”父属性。我还想鼓励通过classget_parent是最简单的方法,但是可以使用其他命令来移动或删除文件夹)的其他方法来访问/更改父信息。

因此,当某人尝试访问f.parent而不是此权限时:

AttributeError: 'Folder' object has no attribute 'parent'

我宁愿得到这样的东西:

AttributeError: 'parent' is a private attribute - you can access the parent through the 'get_parent' method

我看过this post,但还没有弄清楚如何使用。我当时正在考虑使用tryexcept,但我不知道如何应用它,因为当用户调用f.parent时,它需要包含在内。

解决方法

您可以自定义__getattr__的{​​{1}}方法;以下基于this post的示例:

class

有了这个#modified with suggestion from DeepSpace class Folder: def __init__(self,parent=None): self._parent = parent def get_parent(self): return self._parent def __getattr__(self,name): if name == 'parent': raise AttributeError(f"'parent' is a private attribute - you can access the parent through the 'get_parent' method") return super().__getattribute__(name) ,您将获得:

Folder