Python:协议元类带有仅阅读属性的元素
我想实现具有较少样板的只读属性的协议。简而言之:
# 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??
I want to achieve a Protocol with read-only properties with reduced boilerplate. In short:
# 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
I tried a metaclass but something with Protocol makes the property not read-only:
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??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会选择“简单更好”。违反协议背后的直觉可能不值得节省几下按键。
另一个选择是类装饰器,但如果我们首先有能力修改类,那么它似乎没有多大意义。
I'm going to go with "simple is better". Violating the intuition behind Protocols is probably not worth a couple keystrokes of savings.
The other option was class decorators, but if we have the ability to modify the class in the first place it doesn't seem like it makes a lot of sense.