下面是一个示例类Permit
class Permit(object):
def __init__(self):
super(Permit, self).__init__()
# init todo list
self.todo = [1,2,3,4,5]我想做的是:
function
self.todo self.todo列表中注册了一些新元素,但不影响原始的__init__ self.todo必须在调用__init__之后立即修改(就像一个新的__init__ self.todo中,但是元素和插入位置不确定,并由用户指定。
class Permit(object):
def __init__(self):
super(Permit, self).__init__()
# init todo list
self.todo = [1,2,3,4,5]
# new elements
self.todo.insert(6,3)我知道在__init__中添加函数参数可能有帮助,比如def __init__(self, elements, locations):。但是,这种修改是instance-level,当Permit类创建了许多实例时,您必须逐个修改它们。
因此,我想在class-level中注册新元素,这意味着新元素可以在调用__init__函数之后注册(就像修改原始__init__一样)。
我想知道是否可以在某些函数中注册新元素,并确保在调用__init__函数后立即调用它们。
PS:metaclass有帮助吗?如何帮助?
############################################################更新:对不起,我的语言很差,我将在以下几个方面更具体地描述我的需求:
class Permit(object):
def __init__(self):
super(Permit, self).__init__()
# init todo list
self.todo = [1,2,3,4,5]
... # deal with todo listfrom yacs.config import CfgNode as CN
cfg = CN()
...我想做的是:
def add_cfg(cfg):
cfg.method = CN()
cfg.method.param1 = 1.额外的函数文件和一个寄存器
new_element1=1
new_element2=2
registry = {"new_element1": {"class": Permit, "position":-1,}, "new_element2": {"class": Permit, "position":4,}}我不希望用户修改源代码,添加新的信任和方法文件,因为插件是enough.
Permit,Permit2
库中已经调用了,所以我不希望创建像Permit2这样的新的子类。
发布于 2022-02-28 02:31:48
您可以在Python中添加额外的“构造函数”,方法是使用类方法实例化类的实例并对该实例执行修改。
class Permit(object):
def __init__(self):
super(Permit, self).__init__()
# init todo list
self.todo = [1,2,3,4,5]
@classmethod
def with_mod(cls, position, value):
obj = cls()
obj.todo.insert(position, value)
return obj
foo = Permit() # Instance with the default todo list
bar = Permit.with_mod(6, 3) # Instance where the todo list is then modified发布于 2022-03-02 15:58:36
我认为我不太理解您需要什么--但是,如果您可以将自定义元类附加到您的Permit类中,那么元类可以提供帮助:
元类的__call__方法负责创建类的新实例:它将调用类上的__new__,该类将返回一个新的统一实例,然后调用__init__传递它返回的实例__new__,然后再次返回该实例(忽略__init__的返回值)。
如果您想要在__init__之后运行什么,只需将此逻辑添加到自定义元类调用‘:
class PostInit(type): # deriving from type is what makes a metaclass
def __call__(cls, *args, **kw):
instance = super().__call__(*args, **kw) # "instance" now contains the new instance, after __init__ is run
# code to retrieve custom configurations and apply to the instance:
...
return instance
class Permit(metaclass=PostInit):
...https://stackoverflow.com/questions/71289957
复制相似问题