The Python Tutorial 9——Classes

Python类概况:多继承、override、多态

9.1. A Word About Names and Objects

9.2. Python Scopes and Namespaces

三种namespace,不同namespace间同名member互不影响

A namespace is a mapping from names to objects. Most namespaces are currently implemented as Python dictionaries, but that’s normally not noticeable in anyway (except for performance), and it may change in the future. Examples of namespaces are: the set of built-in names (containing functions such asabs(), and built-in exception names);the global names in a module; and the local names ina function invocation.

The important thing to know about namespaces is that there is absolutely no relation between names in different namespaces; for instance, two different modules may both define a functionmaximize without confusion —users of the modules must prefix it with the module name.

生存周期

Namespaces are created at different moments and have different lifetimes. The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted. The global namespace for a module is created when the module definition is read in; normally, module namespaces also last until the interpreter quits. The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively,are considered part of a module called__main__, so they have their ow nglobal namespace. (The built-in names actually also live in a module; this iscalled__builtin__.)

The local namespace for a function is created when the function is called, and deleted when the function returns or raises an exception that is not handled within the function.

9.3. A First Look at Classes

9.3.1. Class Definition Syntax

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>

9.3.2. Class Objects

类对象支持两种操作:引用和实例化

Class objects support two kinds of operations: attribute references andinstantiation.

Attribute references use the standard syntax used for all attribute referencesin Python:obj.name.

class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'
then MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively.
Class instantiation uses function notation.

x = MyClass()

9.3.3. Instance Objects

There are two kinds of validattribute names, data attributes and methods.

Data attributes need not be declared

x.counter = 1
while x.counter < 10:
    x.counter = x.counter * 2
print x.counter
del x.counter
A method is a function that “belongs to” an object.

9.3.4. Method Objects

A method object can be stored away and called at a later time  个人感觉是方法可以别名,方便后面简化调

xf = x.f
while True:
    print xf()
函数调用时类实例作为第一个参数隐式传入

9.3.5. Class and Instance Variables

9.4. Random Remarks

Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python.

Methods in the same class may call other methods by using method attributes of theself argument:

class Bag:
    def __init__(self):
        self.data = []
    def add(self, x):
        self.data.append(x)
    def addtwice(self, x):
        self.add(x)
        self.add(x)

9.5. Inheritance

class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>
Derived classes may override methods of their base classes.(For C++ programmers: all methods in Python are effectively virtual.)

9.5.1. Multiple Inheritance

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>

9.6. Private Variables and Class-local References

没太看懂o(╯□╰)o

9.7. Odds and Ends

class Employee:
    pass

john = Employee() # Create an empty employee record

# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000

9.8. Exceptions Are Classes Too

A class in an except clause is compatible with an exception if it is the same class or a base class thereof. Forexample, the following code will print B, C, D in that order:
class B:
    pass
class C(B):
    pass
class D(C):
    pass

for c in [B, C, D]:
    try:
        raise c()
    except D:
        print "D"
    except C:
        print "C"
    except B:
        print "B"

Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except clause is triggered.

9.9. Iterators

By now you have probably noticed that most container objects can be looped over using a for statement:

for element in [1, 2, 3]:
    print element
for element in (1, 2, 3):
    print element
for key in {'one':1, 'two':2}:
    print key
for char in "123":
    print char
for line in open("myfile.txt"):
    print line,
另一种方式 the for statement calls iter()
>>> s = 'abc'
>>> it = iter(s)
>>> it
<iterator object at 0x00A1DB50>
>>> it.next()
'a'
>>> it.next()
'b'
>>> it.next()
'c'
>>> it.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
    it.next()
StopIteration

9.10. Generators

Generators are a simple and powerful tool for creating iterators. Theyare written like regular functions but use the yield statement whenever they want to return data. Each time next() is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed). An example shows that generators can be trivially easy to create:
def reverse(data):
    for index in range(len(data)-1, -1, -1):
        yield data[index]

>>> for char in reverse('golf'):
...     print char
...
f
l
o
g

9.11. Generator Expressions


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值