有没有一种方法可以在Python中定义子类的方法? [英] Is there a way to call a method on definition of a subclass in Python?

查看:151
本文介绍了有没有一种方法可以在Python中定义子类的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

__init__方法定义在创建类的实例时要执行的操作.创建子类时,我可以做一些等效的事情吗?

The __init__ method defines what is done on creating an instance of a class. Can I do something equivalent when a subclass is created?

假设我有抽象类Entity:

class Entity:
    def __onsubclasscreation__(cls):
        for var in cls.__annotations__:
            cls.__dict__[var] = property(lambda self:self.vars[var])

这意味着每当我定义一个继承自Entity的新类时,该类的所有带注释的变量都将收到一个吸气剂:

This would mean that whenever I define a new class inheriting from Entity, all annotated variables of that class would receive a getter:

class Train(Entity):
    wagons: int
    color: str

>>> t = Train()
>>> t.vars["wagons"] = 5
>>> t.wagons
5

我无法在实例化上执行此操作,因为属性需要在类中定义,而我无法在超类中执行此操作,因为我不知道将需要哪些属性.有什么方法可以动态地创建子类吗?

I can't do this on instantiation because properties need to be defined in the class, and I can't do it in the superclass because I don't know which attributes will be needed. Is there any way to do something dynamically on subclass creation?

推荐答案

您正在描述__init_subclass__挂钩的基本用法(

You are describing the basic usage of __init_subclass__ hook (docs):

只要一个类继承自另一个类,就会在该类上调用__init_subclass__.这样,可以编写更改子类行为的类.

Whenever a class inherits from another class, __init_subclass__ is called on that class. This way, it is possible to write classes which change the behavior of subclasses.

>>> class A: 
...     def __init_subclass__(cls): 
...         print(f"init {cls}") 
...
>>> class B(A): 
...     pass 
...
init <class '__main__.B'>

有关更多信息,请参见 PEP 487-类创建的更简单自定义信息.

See PEP 487 -- Simpler customisation of class creation for more information.

注意:这是3.6+版本的功能.在较旧的Python版本中,请使用元类__new__来实现相同的目的:

Note: This is a 3.6+ feature. In older Python versions, use the metaclass __new__ to achieve same:

>>> class MyMeta(type):
...     def __new__(meta, name, bases, class_dict):
...         print("MyMeta.__new__", meta, name, bases, class_dict)
...         return type.__new__(meta, name, bases, class_dict)
...
>>> class A(metaclass=MyMeta):
...     pass
...
MyMeta.__new__ <class '__main__.MyMeta'> A () {'__module__': '__main__', '__qualname__': 'A'}
>>> class B(A):
...     pass
...
MyMeta.__new__ <class '__main__.MyMeta'> B (<class '__main__.A'>,) {'__module__': '__main__', '__qualname__': 'B'}

这篇关于有没有一种方法可以在Python中定义子类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆