python 多继承 __new___带有继承的Python __new__元类行为

本文探讨了Python中类的元类行为,特别是`__new__`方法在非实例化过程中的调用。`__new__`不仅控制实例的创建,还涉及类的定义阶段。同时,解释了`__delattr__`为何在`hasattr`返回True的情况下仍会引发AttributeError,原因在于`size`是类属性而非实例属性。博客深入理解了类属性与实例属性的区别,以及元类在Python中的工作原理。
摘要由CSDN通过智能技术生成

I have two questions regarding the behavior of running the below code. Why is __new__ even being called without instantiating an object? I thought __new__ controlled the creation of a new instance. Next, why does delattr raise an AttributeError when hasattr returns True for size?

class ShapeBase(type):

def __new__(cls, name, bases, attrs):

rv = super(ShapeBase, cls).__new__(cls, name, bases, attrs)

parents = [base for base in bases if isinstance(base, ShapeBase)]

# don't do anything unless this is a subclass of Shape

if not parents:

return rv

print hasattr(rv, 'altitude') # prints True

print rv.altitude # prints 7

del rv.altitude # deletes altitude from rv

print hasattr(rv, 'size') # prints True

print rv.size # prints 5

delattr(rv, 'size') # raises AttributeError

return rv

class Shape(object):

__metaclass__ = ShapeBase

size = 5

class Triangle(Shape):

altitude = 7

解决方案

For the second question delattr(rv, 'size') (and del rv.size) is failing because the attribute size is a class attribute not an instance attribute which mean is part of the class __dict__ not the instance __dict__.

And the hasattr normally will return True because it search for an attribute in all the parent classes of the object passed to it.

As for why your metaclass __new__ is called when the class body is evaluated think of it like this :

If you create an instance of a class the class __new__ will be called when you create the instance, yes ? so the same should apply on class , a metaclass is a class of a class so the __new__ will be called when you create the class.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值