Python:协议元类带有仅阅读属性的元素

发布于 2025-01-19 17:59:40 字数 874 浏览 2 评论 0原文

我想实现具有较少样板的只读属性的协议。简而言之:

# 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一页 2025-01-26 17:59:40

我会选择“简单更好”。违反协议背后的直觉可能不值得节省几下按键。

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文