Python学习笔记(三十一)高级的类话题(Advanced Class Topics)

1.说出两种扩展内建对象类型(built-in object type)的方法。
答:您可以在包装类(wrapper class)中嵌入内置对象,或直接为内置类型创建子类(subclass)。后一种方法往往更简单,因为大多数原始行为都是自动继承的。

 

2.什么是函数和类装饰器(decorators)?
答:函数装饰器通常用于管理函数或方法,或者在每次调用函数或方法时添加一层逻辑。它们可用于记录或计算对函数的调用的次数,检查其参数类型等。它们还用于“声明”静态方法(在调用时未传递实例的类中的简单函数),以及类方法和属性。类装饰器类似,但管理整个对象及其接口而不是函数调用。

 

3.你如何编写一个新式(new-style)的类?
答:通过从对象内置类(或任何其他内置类型)继承来编写新样式类。在Python 3.X中,所有类都是自动的新式类,因此这种派生不是必需的(但不会有问题);在2.X中,具有这种显式派生的类是新式的,没有它的类是“经典的”。

 

4.新风格和经典类有何不同?
答:新式类以不同方式搜索多个继承树的diamond模式- 它们在diamond树中基本上搜索广度优先(横跨),而不是深入优先(向上)。新式类还更改了实例和类的内置类型的结果,不为内置操作方法运行泛型属性获取方法,如__get attr__,并支持一组高级的额外工具,包括属性(properties),描述器(descriptors), super和__slots__实例属性列表。

 

5.正常和静态方法有何不同?
答:普通(实例)方法接收self参数(隐含实例),但静态方法不接收。静态方法是嵌套在类对象中的简单函数。要使方法静态,必须通过特殊的内置函数运行或使用装饰器语法进行修饰。 Python 3.X允许在没有这一步的情况下通过类调用类中的简单函数,但是通过实例调用仍然需要静态方法声明。

 

6.在您的代码中使用__slots__和super是有效的工具吗?
答:当然,但如果不仔细考虑它们的含义,就不应自动使用高级的工具。例如,slots可能会破坏代码; super用于单继承时可以掩盖问题,并且在多继承中为单独的用例(isolated use case)带来了相当大的复杂性;并且都要求通用部署最有用。评估新工具或高级工具是任何工程师的首要任务,也是我们在本章中仔细探讨权衡的原因。本书的目标不是告诉您使用哪些工具,而是强调客观分析它们的重要性 - 这一任务通常在软件领域中的优先级太低。

 

7.在投掷“圣 · 手榴弹(Holy Hand Grenade)”之前,你还要等多久?
答:三秒钟。 (或者,更准确地说:“耶和华说,'你先取出圣针。然后,你要数到三,不多,不少。你要数三个,数的要三个。你不可数四,也不可数二,除非你接着数到三。五是立马行动。一旦达到第三个数字,那么你就把你神圣的 Antioch 圣 · 手榴弹扔向你的敌人,因为敌人在我看来很顽皮,会把它消灭掉的。“

 

使用OOP最常见的原因

1.代码重用(Code reuse)
这个很容易(也是使用OOP的主要原因)。通过支持继承,类允许您通过自定义编程,而不是从头开始每个项目。
2.封装(Encapsulation)
在对象接口后面包含实现细节可以使类的用户与代码更改隔离开来。
3.架构(Structure)
类提供了新的局部范围,可最大限度地减少名称冲突。它们还提供了一个自然的位置来编写和查找实现代码,以及管理对象状态。
4.保养(Maintenance)
类自然地促进了代码分解,这使我们能够最大限度地减少冗余。由于类的结构和代码重用支持,通常只需要更改代码的一个副本。
5.一致性(Consistency)
类和继承允许您实现通用接口,从而在代码中创建一个通用的外观;这样可以简化调试,理解和维护。
6.多态性(Polymorphism )
这更像是OOP的一个属性,而不是使用它的原因,但是通过支持代码的通用性,多态性使代码更加灵活和广泛适用,因此更具可重用性。
7.其他(Other)
当然,这也是学生们使用OOP的首要原因:它在一个简历上看起来很棒! (好吧,我把这个作为一个笑话,但如果你打算今天在软件领域工作,那么熟悉OOP很重要。)

 

注:转载《Learning Python 5th Edition》[奥莱理]

1. Name two ways to extend a built-in object type.
2. What are function and class decorators used for?
3. How do you code a new-style class?
4. How are new-style and classic classes different?
5. How are normal and static methods different?
6. Are tools like __slots__ and super valid to use in your code?
7. How long should you wait before lobbing a “Holy Hand Grenade”?


1. You can embed a built-in object in a wrapper class, or subclass the built-in type directly. The latter approach tends to be simpler, as most original behavior is automatically inherited.
2. Function decorators are generally used to manage a function or method, or add to it a layer of logic that is run each time the function or method is called. They can be used to log or count calls to a function, check its argument types, and so on. They are also used to “declare” static methods (simple functions in a class that are not passed an instance when called), as well as class methods and properties. Class decorators are similar, but manage whole objects and their interfaces instead of a function call.
3. New-style classes are coded by inheriting from the object built-in class (or any other built-in type). In Python 3.X, all classes are new-style automatically, so this derivation is not required (but doesn’t hurt); in 2.X, classes with this explicit derivation are new-style and those without it are “classic.”
4. New-style classes search the diamond pattern of multiple inheritance trees differently—they essentially search breadth-first (across), instead of depth-first (up) in diamond trees. New-style classes also change the result of the type built-in for instances and classes, do not run generic attribute fetch methods such as __get attr__ for built-in operation methods, and support a set of advanced extra tools including properties, descriptors, super, and __slots__ instance attribute lists.
5. Normal (instance) methods receive a self argument (the implied instance), but static methods do not. Static methods are simple functions nested in class objects. To make a method static, it must either be run through a special built-in function or be decorated with decorator syntax. Python 3.X allows simple functions in a class to be called through the class without this step, but calls through instances still require static method declaration.
6. Of course, but you shouldn’t use advanced tools automatically without carefully considering their implications. Slots, for example, can break code; super can masklater problems when used for single inheritance, and in multiple inheritance brings with it substantial complexity for an isolated use case; and both require universal deployment to be most useful. Evaluating new or advanced tools is a primary task of any engineer, and is why we explored tradeoffs so carefully in this chapter. This book’s goal is not to tell you which tools to use, but to underscore the importance of objectively analyzing them—a task often given too low a priority in the software field.
7. Three seconds. (Or, more accurately: “And the Lord spake, saying, ‘First shalt thou take out the Holy Pin. Then, shalt thou count to three, no more, no less. Three shalt be the number thou shalt count, and the number of the counting shall be three. Four shalt thou not count, nor either count thou two, excepting that thou then proceed to three. Five is right out. Once the number three, being the third number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch towards thy foe, who, being naughty in my sight, shall snuff it.’”)4

 

Code reuse
This one’s easy (and is the main reason for using OOP). By supporting inheritance, classes allow you to program by customization instead of starting each project from scratch. 
Encapsulation
Wrapping up implementation details behind object interfaces insulates users of a class from code changes.
Structure
Classes provide new local scopes, which minimizes name clashes. They also provide a natural place to write and look for implementation code, and to manage object state.
Maintenance
Classes naturally promote code factoring, which allows us to minimize redundancy. Thanks both to the structure and code reuse support of classes, usually only one copy of the code needs to be changed.
Consistency
Classes and inheritance allow you to implement common interfaces, and hence create a common look and feel in your code; this eases debugging, comprehension, and maintenance.
Polymorphism 
This is more a property of OOP than a reason for using it, but by supporting code generality, polymorphism makes code more flexible and widely applicable, and hence more reusable.
Other
And, of course, the number one reason students gave for using OOP: it looks good on a résumé! (OK, I threw this one in as a joke, but it is important to be familiar with OOP if you plan to work in the software field today.)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值