gpt4 book ai didi

实例属性的 Python NotImplementedError

转载 作者:太空宇宙 更新时间:2023-11-04 08:26:08 25 4
gpt4 key购买 nike

如何将 instance 属性标记为未在基类中实现? (与讨论将 class 属性标记为未实现的 this 问题不同,但也许我没有正确理解基类...)

例如我想要类似的东西

class Base():
def __init__(self):
self.x = NotImplemented

class GoodSub(Base):
def __init__(self, x):
super().__init__()
self.x = x #good

class BadSub(Base):
def __init__(self):
super().__init__()
#forgot to set self.x

good = GoodSub(5)
bad = BadSub(-1)
good.x #returns 5
bad.x #throws error because x not implemented

或者,是否有更好的方法强制 Base 的所有子类在初始化时设置 self.x 属性?

编辑:link to related question

最佳答案

一种带有类装饰器和描述符的解决方案(__get__ 方法):

def abstract_variables(*args):
class av:
def __init__(self, error_message):
self.error_message = error_message

def __get__(self, *args, **kwargs):
raise NotImplementedError(self.error_message)

def f(klass):
for arg in args:
setattr(klass, arg, av('Descendants must set variable `{}`'.format(arg)))
return klass

return f


@abstract_variables('x', 'y')
class Base:
def __init__(self):
pass

class Derived(Base):
x = 10


b = Base()
d = Derived()
print(d.x) # prints 10
print(d.y) # raises NotImplementedError

打印:

10
Traceback (most recent call last):
File "main.py", line 28, in <module>
print(d.y)
File "main.py", line 7, in __get__
raise NotImplementedError(self.error_message)
NotImplementedError: Descendants must set variable `y`

关于实例属性的 Python NotImplementedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56997102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com