Python - 我需要学习旧式类吗?

发布于 2024-10-18 09:20:55 字数 241 浏览 5 评论 0原文

我目前正在学习Python 2.6.5,我发现了旧样式类和新样式类。

我知道这些类仍然存在只是为了向后兼容,并且它们在 Python 3 中被删除。

所以问题是:作为该语言的新手,我需要学习经典类吗?

PS我正在学习Python 2,因为Python 3在框架中仍然没有完全支持,我也想学习一些框架。计划是当框架迎头赶上时迁移到 Python 3,但在那之前,我需要担心旧样式的类吗?

I am currently learning Python 2.6.5 and I found out about old style classes and new style classes.

I understand that these classes are still existing only for backward compatibility and that they are removed in Python 3.

So the question is this: as a newcomer to the language, do I need to learn about the classic classes?

P.S. I am learning Python 2 because Python 3 is still not fully supported in frameworks and I want to learn some frameworks too. The plan will be to move to Python 3 when frameworks catch up, but until then, do I need to worry about the old style classes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

肥爪爪 2024-10-25 09:20:55

不,别打扰。只需从 object(或从 object 继承的类)继承所有类,就可以了。然后,当您过渡到 Python 3 时,您可能会忘记那一点语法。

此时使用甚至学习旧式类都没有任何优势。

因此,只需确保所有类声明如下所示:(

class foo(object):
    ...

或者继承自 object 之外的对象,而 确实继承自 object),并且然后假装这就是一直以来的样子!

No. Don't bother. Simply inherit all your classes from object (or from classes that inherit from object) and you will be good to go. Then when you transition to Python 3 you can forget that bit of syntax.

There's no advantage to using or even learning about old-style classes at this point.

So just make sure all of your class declarations look like this:

class foo(object):
    ...

(or inherit from something other than object which does inherit from object), and then pretend this is the way that it has always been!

沩ん囻菔务 2024-10-25 09:20:55

尽管我同意 Daniel DiPaolo 的观点,即您永远不需要在代码中使用旧式类,但有时您需要稍微了解它们。

例如,对于旧式类,您不能使用 super 来调用父方法 - 当您尝试子类化时,这可能会困扰您,例如 urllib2.Request代码>类。如果您在没有意识到的情况下执行此操作,则会收到神秘错误 super() argument 1 must be type, not classobj,这可能需要很长时间才能调试。

(你可能知道,我去过那里......)

Although I agree with Daniel DiPaolo that you should never need to use old-style classes in your code, there will be times when you will need to understand them a little bit.

For example, with old-style classes you can't use super to call a parent method - and this can bite you when you try and subclass, for example, the urllib2.Request class. If you do this without realising you'll get the cryptic error super() argument 1 must be type, not classobj, which can take ages to debug.

(As you can probably tell, I've been there...)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文