马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 永恒的蓝色梦想 于 2020-6-30 18:18 编辑
简介:
模仿 C# 的静态类。
经由这个装饰器装饰的类将无法被继承,且无法实例化,而且无法包含普通方法。
示例:>>> @staticclass
class p:
...
>>> p()
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
p()
File "<pyshell#1>", line 12, in __new__
raise TypeError("Can't instantiate abstract class "+cls.__name__)
TypeError: Can't instantiate abstract class p
>>> class b(p):
pass
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
class b(p):
File "<pyshell#1>", line 8, in __init_subclass__
raise TypeError("type '"+cls.__name__ +
TypeError: type 'p' is not an acceptable base type
>>> @staticclass
class f:
def function(self):
return 0
Traceback (most recent call last):
File "<pyshell#15>", line 2, in <module>
class f:
File "<pyshell#1>", line 4, in staticclass
raise TypeError(
TypeError: Can't define non-static members in static class f
>>> @staticclass
class n:
@staticmethod
def fads():
return 6
@classmethod
def ewfds(cls):
return 8
list=[]
tuple=()
string=''
set=set()
dict={}
class t:
pass
>>> n.fads
<function n.fads at 0x000001583E9A89D0>
>>> n.ewfds
<bound method n.ewfds of <class '__main__.n'>>
>>> n.list
[]
>>> n.tuple
()
>>> n.string
''
>>> n.set
set()
>>> n.dict
{}
>>> n.t
<class '__main__.n.t'>
代码:function = (lambda: None).__class__
def staticclass(cls: type, / ) -> type:
for i in vars(cls).values():
if i.__class__ is function:
raise TypeError(
"Can't define non-static members in static class "+cls.__name__)
def __init_subclass__(ncls: type, / ) -> None:
raise TypeError("type '"+cls.__name__ +
"' is not an acceptable base type")
def __new__(ncls: type, / , *args, **kwargs) -> None:
raise TypeError("Can't instantiate abstract class "+cls.__name__)
cls.__init_subclass__ = classmethod(__init_subclass__)
cls.__new__ = staticmethod(__new__)
return cls
|