Python - 我需要学习旧式类吗?
我目前正在学习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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,别打扰。只需从
object
(或从object
继承的类)继承所有类,就可以了。然后,当您过渡到 Python 3 时,您可能会忘记那一点语法。此时使用甚至学习旧式类都没有任何优势。
因此,只需确保所有类声明如下所示:(
或者继承自
object
之外的对象,而 确实继承自object
),并且然后假装这就是一直以来的样子!No. Don't bother. Simply inherit all your classes from
object
(or from classes that inherit fromobject
) 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:
(or inherit from something other than
object
which does inherit fromobject
), and then pretend this is the way that it has always been!尽管我同意 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, theurllib2.Request
class. If you do this without realising you'll get the cryptic errorsuper() argument 1 must be type, not classobj
, which can take ages to debug.(As you can probably tell, I've been there...)