使用从 json 键定义的抽象方法创建 ABC
Create an ABC with abstract methods defined from json keys
假设我有一个 json 文件,如下所示:
{
"foo": ["hi", "there"],
"bar": ["nothing"]
}
我想创建一个抽象基础class(ABC),其中抽象方法的名称是上面json的键,即:
from abc import ABCMeta, abstractmethod
class MyABC(metaclass=ABCMeta):
@abstractmethod
def foo(self):
pass
@abstractmethod
def bar(self):
pass
问题是 json 文件实际上有很多密钥。我想知道有没有这样的方法:
import json
with open("the_json.json") as f:
the_json = json.load(f)
class MyABC(metaclass=ABCMeta):
# for k in the_json.keys():
# create abstract method k
感谢评论中的建议,但不知何故没有按预期工作。这是我尝试过的:
class MyABC(metaclass=ABCMeta):
pass
def f(self):
pass
setattr(MyABC, "foo", abstractmethod(f))
# I also tried
# setattr(MyABC, "foo", abstractmethod(lambda self: ...))
# Try to define another class that inherits MyABC
class MyClass(MyABC):
pass
c = MyClass()
# Now this should trigger TypeError but it doesn't
# I can even call c.foo() without getting any errors
这可能有效:
from abc import ABCMeta, abstractmethod
with open("the_json.json") as f:
the_json = json.load(f)
class MyABC(metaclass=ABCMeta):
def func(self):
pass
for k in the_json:
locals()[k] = abstractmethod(func)
# Delete attribute "func" is a must
# Otherwise it becomes an additional abstract method in MyABC
delattr(MyABC, "func")
delattr(MyABC, "f")
delattr(MyABC, "k")
class MyClass(MyABC):
pass
MyClass()
# TypeError: Can't instantiate abstract class MyClass with abstract methods bar, foo
如果您尝试实例化 MyABC 或未实现抽象方法的 MyABC 的子类,它将正确地抛出错误。
假设我有一个 json 文件,如下所示:
{
"foo": ["hi", "there"],
"bar": ["nothing"]
}
我想创建一个抽象基础class(ABC),其中抽象方法的名称是上面json的键,即:
from abc import ABCMeta, abstractmethod
class MyABC(metaclass=ABCMeta):
@abstractmethod
def foo(self):
pass
@abstractmethod
def bar(self):
pass
问题是 json 文件实际上有很多密钥。我想知道有没有这样的方法:
import json
with open("the_json.json") as f:
the_json = json.load(f)
class MyABC(metaclass=ABCMeta):
# for k in the_json.keys():
# create abstract method k
感谢评论中的建议,但不知何故没有按预期工作。这是我尝试过的:
class MyABC(metaclass=ABCMeta):
pass
def f(self):
pass
setattr(MyABC, "foo", abstractmethod(f))
# I also tried
# setattr(MyABC, "foo", abstractmethod(lambda self: ...))
# Try to define another class that inherits MyABC
class MyClass(MyABC):
pass
c = MyClass()
# Now this should trigger TypeError but it doesn't
# I can even call c.foo() without getting any errors
这可能有效:
from abc import ABCMeta, abstractmethod
with open("the_json.json") as f:
the_json = json.load(f)
class MyABC(metaclass=ABCMeta):
def func(self):
pass
for k in the_json:
locals()[k] = abstractmethod(func)
# Delete attribute "func" is a must
# Otherwise it becomes an additional abstract method in MyABC
delattr(MyABC, "func")
delattr(MyABC, "f")
delattr(MyABC, "k")
class MyClass(MyABC):
pass
MyClass()
# TypeError: Can't instantiate abstract class MyClass with abstract methods bar, foo
如果您尝试实例化 MyABC 或未实现抽象方法的 MyABC 的子类,它将正确地抛出错误。