从Python中的`object`派生类 [英] Deriving class from `object` in python

查看:64
本文介绍了从Python中的`object`派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我只是在学习python(我知道许多其他语言),我对某些事情感到困惑。我认为这是由于缺乏文档(至少可以找到)。在一些网站上,我读到您应该从 object 派生类:

So I'm just learning python (I know plenty of other languages) and I'm confused about something. I think this is due to lack of documentation (at least that I could find). On a few websites, I've read that you should derive your classes from object:



class Base(object):
    pass

但是我不知道这样做是什么,为什么或者什么时候应该这样做。是否有我错过的官方文档?这是3.x功能吗?

But I don't see what that does or why or when you should do it. Is there official documentation on this that I've missed? Is this a 3.x feature?

推荐答案

在大多数情况下,是否从对象继承都无关紧要,但是如果您不这样做,那么当您忘记决定不去打扰的时候,就会有许多错误等待着您。

Mostly it isn't going to matter whether or not you inherit from object, but if you don't there are bugs waiting to catch you out when you've forgotten that you decided not to bother.

如果某些细微的事情不能正常工作,您最终不会从对象继承:

Some subtle things just won't work properly if you don't ultimately inherit from object:


  1. 在经典类中使用属​​性只能部分起作用: get 可以正常工作,但是 set 确实很奇怪。

  2. 经典类中的多重继承与从对象派生的类中的多重继承行为不同

  3. 如果您尝试将经典类与那些子类对象混合使用,那么多重继承将不起作用。

  1. Using properties in classic classes only partly works: get works alright, but set does weird things.
  2. Multiple inheritance behaves differently in classic classes than in classes derived from object.
  3. Also multiple inheritance won't work if you try to mix classic classes with those that subclass object. Whatever you do you want to be consistent.

某些人可以继续使用经典类,除非他们需要新的行为,其他人则说,一定要使用新样式的类,以免日后被自己的脚打伤。如果您正在做一个人的项目,那么做对自己有好处的事情;如果它的共享项目与其他开发人员一致。

Some people are fine with continuing to use classic classes except when they need the new behaviour, others say to always use new style classes to avoid later shooting yourself in the foot. If you're working on a single person project do whatever is good for you; if its a shared project be consistent with the other developers.

这篇关于从Python中的`object`派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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