我有一个星球的硕士班:
class Planet:
def __init__(self,name):
self.name = name
(...)
def destroy(self):
(...)
我还有一些从Planet
继承的类,我想让其中一个不能被销毁(不是继承destroy
函数)
示例:
^{pr2}$所以当这一切开始的时候
Undestroyable('This Planet').destroy()
它会产生如下错误:
AttributeError: Undestroyable has no attribute 'destroy'
其他答案中的mixin方法很好,而且可能在大多数情况下更好。但无论如何,它破坏了部分乐趣-也许迫使你有单独的星球等级-像必须生活在两个抽象类的祖先“可摧毁”和“不可摧毁”。在
第一种方法:描述符修饰符
但是Python有一种强大的机制,叫做“描述符协议”,用于从类或实例中检索任何属性,甚至通常用于从实例中检索方法,因此,可以通过检查方法检索是否“应该属于”该类来定制方法检索,否则会引发属性错误。在
描述符协议规定,每当您试图从Python中的实例对象获取任何属性时,Python将检查该属性是否存在于该对象的类中,如果存在,则检查该属性本身是否具有名为
__get__
的方法。如果有,则调用__get__
(使用实例和类将其定义为参数),并且返回的是属性。Python使用它来实现方法:python3中的函数有一个__get__
方法,当调用该方法时,它将返回另一个可调用对象,而当调用该对象时,它将在对原始函数的调用中插入self
参数。在因此,可以创建一个类,该类的
__get__
方法将决定是否将函数作为绑定方法返回,这取决于外部类是否标记为So—例如,它可以检查特定的标志non_destrutible
。这可以通过使用decorator用描述符功能包装方法来完成在交互式提示下:
^{pr2}$请注意,与简单地重写方法不同,此方法在检索属性时会引发错误,甚至会使
hasattr
工作:但是,如果试图直接从类中而不是从实例中检索方法,那么它将不起作用——在这种情况下,
instance
参数被设置为None,而且我们不能说它是从哪个类中检索的——只需要声明它的owner
类。在第二种方法:
__delattr__
在元类上:在写上述内容时,我突然想到Pythn确实有
__delattr__
特殊方法。如果Planet
类本身实现了__delattr__
,并且我们试图删除特定派生类上的destroy
方法,它将无法工作:__delattr__
禁止实例中属性的属性删除-如果您试图在实例中del
调用“destroy”方法,它无论如何都会失败,因为该方法在类中。在然而,在Python中,类本身就是它的“元类”的一个实例。通常是
type
。“Planet”元类上的一个适当的__delattr__
可以通过发出一个'del'来实现“destroy”方法的“deshinity”不可摧毁的飞机。摧毁“课后创作。在同样,我们使用描述符协议来拥有一个适当的“删除子类的方法”:
使用此方法,即使尝试检索或检查类本身存在的方法也会起作用:
具有自定义
__prepare__
方法的元类由于元类允许自定义包含类名称空间的对象,因此可以在类主体中添加一个响应
del
语句的对象,并添加一个Deleted
描述符。在对于使用此元类的用户(程序员),它几乎是相同的,但是对于
del
语句,它被允许进入类主体本身:(“deleted”描述符是将方法标记为“deleted”的正确形式-但是在这个方法中,它在类创建时无法知道类名)
作为班级装饰师:
如果使用“deleted”描述符,您可以简单地将要删除的方法作为类装饰器删除-不需要f或者本例中的元类:
修改
__getattribute__
机制:为了完整性起见,真正让Python访问超级类上的方法和属性的是
__getattribute__
调用中发生的事情。n在object
版本的__getattribute__
中,对属性检索的具有“数据描述符、实例、类、基类链等”优先级的算法进行编码。在因此,对类进行更改是一个简单的独特点,可以获得“合法”的属性错误,而不需要前面的方法中使用的“不存在”描述符。在
问题是}就足够了。必须在实例上这样做以避免方法的实例查找,而在元类上这样做可以避免元类查找。当然,元类可以注入所需的代码:
object
的__getattribute__
没有使用type
的一个来搜索类中的属性-如果这样做了,只在元类上实现{如果
Undestroyable
是一个唯一的(或至少不寻常的)情况,那么重新定义destroy()
可能是最简单的:从类的用户的角度来看,这将表现为
Undestroyable.destroy()
不存在……除非他们使用hasattr(Undestroyable, 'destroy')
四处寻找,这总是有可能的。在如果您希望子类继承一些属性而不是其他属性,那么chepner's answer中的mixin方法可能更易于维护。您可以通过使
^{pr2}$Destructible
和abstract base class来进一步改进它:这样做的好处是,如果您尝试实例化抽象类
Destructible
,您将得到一个指向问题的错误:…类似地,如果从
Destructible
继承,但忘记定义destroy()
:与其删除继承的属性,不如通过mix-in类在子类中继承
destroy
。这保留了继承的正确“is-a”语义。在您可以在}继承的任何类中为
Destructible
、Planet
或从{destroy
提供合适的定义。在相关问题 更多 >
编程相关推荐