繁体   English   中英

Python:具有只读属性的协议元类

[英]Python: Protocol metaclass with read-only properties

我想实现一个具有只读属性并减少样板文件的协议。 简而言之:

# I want to reduce boilerplate of the following.
class MyVerboseProtocol(Protocol)
    @property
    def x(self):
        return x


# I want this to be functionally equivalent to MyVerboseProtocol
class MyProtocol(Protocol)
     x # this should be read-only


class MyClass(MyProtocol)
    x = 5


my_class = MyClass()
print(my_class.x) # should print 5
myclass.x = 4 # should raise some exception

我尝试了一个元类,但是带有协议的东西使该属性不是只读的:

class MyMetaProtocol(type(Protocol) # needs type(Protocol) or something won't resolve
    @property
    def x(self): # pylance seems to want self here
        return self.x


class MyProtocol(Protocol, metaclass=MyMetaProtocol)
    x


class MyClass(MyProtocol)
    x = 5


my_class = MyClass()
print(my_class.x) # should print 5
myclass.x = 4 # seems fine??

我要去 go,“越简单越好”。 违反协议背后的直觉可能不值得节省几次按键。

另一个选项是 class 装饰器,但如果我们有能力首先修改 class,那么它似乎没有多大意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM