[英]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.