python子类_有没有一种方法可以在Python中定义子类的方法?

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

Let's say I have the abstract class Entity:

class Entity:

def __onsubclasscreation__(cls):

for var in cls.__annotations__:

cls.__dict__[var] = property(lambda self:self.vars[var])

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?

解决方案

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

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

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__ A () {'__module__': '__main__', '__qualname__': 'A'}

>>> class B(A):

... pass

...

MyMeta.__new__ B (,) {'__module__': '__main__', '__qualname__': 'B'}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值