python里foo_Python中类foo和类foo(object)的区别

Prior to python 2.2 there were essentially two different types of class: Those defined by C extensions and C coded builtins (types) and those defined by python class statements (classes). This led to problems when you wanted to mix python-types and builtin types. The most common reason for this is subclassing. If you wanted to subclass the list type in python code, you were out of luck, and so various workarounds were used instead, such as subclassing the pure python implementation of lists (in the UserList module) instead.

This was a fairly ugly, so in 2.2 there was a move to unify python and builtin types, including the ability to inherit from them. The result is "new style classes". These do have some incompatible differences to old-style classes however, so for backward compatability the bare class syntax creates an old-style class, while the new behaviour is obtained by inheriting from object. The most visible behaviour differences are:

The method resolution order (MRO). There is a difference in behaviour in diamond-shaped inheritance hierarchies (where A inherits from both B and C, which both inherit from a common base class D. Previously, methods were looked up left-to right, depth first (ie A B D C D) However if C overloads a member of D, it won't be used by A (as it finds D's implementation first) This is bad for various styles of programming (eg. using mixin classes). New style classes will treat this situation as A B C D, (look at the __mro__ attribute of a class to see the order it will search)

The __new__ constructor is added, which allows the class to act as a factory method, rather than return a new instance of the class. Useful for returning particular subclasses, or reusing immutable objects rather than creating new ones without having to change the creation interface.

Descriptors. These are the feature behind such things as properties, classmethods, staticmethods etc. Essentially, they provide a way to control what happens when you access or set a particular attribute on a (new style) class.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值