美文网首页原理和语言
The Python Tutorial - C9 Classes

The Python Tutorial - C9 Classes

作者: 左心Chris | 来源:发表于2019-07-24 14:18 被阅读0次

    https://docs.python.org/3/tutorial/index.html

    9.1 Names and Objects

    Multiple names can be bound to the same object. It can be safely ignored when dealing with immutable basic types (numbers, strings, tuples). However, aliasing has a possibly surprising effect on the semantics of Python code involving mutable objects such as lists, dictionaries, and most other types.

    9.2 Scopes and Namespaces

    • Namespace is a mapping from names to objects.
      即命名空间是名字到对象的映射

    • Namespace are created at different moments and have different lifetimes.
      such as:
      build-in names(builtins); global namespace; statements called main has their own global namespace; local namespace
      即有全局,函数,main命名空间

    • Scope is a textual region of a python program where a namespace is directly accessible.

    • If a name is declared global, then all references and assignments go directly to the middle scope containing the module’s global names. To rebind variables found outside of the innermost scope, the nonlocal statement can be used; if not declared nonlocal, those variables are read-only (an attempt to write to such a variable will simply create a new local variable in the innermost scope, leaving the identically named outer variable unchanged).
      声明了global,那么更改了对全局都有影响;声明了nonlocal,那么对上一层有影响

    9.2.1 scopes and namespaces example

    • Note how the local assignment (which is default) didn’t change scope_test’s binding of spam. The nonlocal assignment changed scope_test’s binding of spam, and the global assignment changed the module-level binding.

    关于命名空间和作用域更细致的解释:

    https://www.jianshu.com/p/555598495cc6
    通过字典实现:globals() locals()

    • Local(innermost)
      包含局部变量,比如一个函数/方法内部。
    • Enclosing
      包含了非局部(non-local)也非全局(non-global)的变量。比如两个嵌套函数,内层函数可能搜索外层函数的namespace,但该namespace对内层函数而言既非局部也非全局。
    • Global(next-to-last)
      当前脚本的最外层,比如当前模块的全局变量。
    • Built-in(outtermost)
      Python builtin 模块。包含了内建的变量/关键字等。

    9.3 First look at classes

    9.3.1 class definition syntax

    class ClassName:
      <statement>
      <statement>
    

    9.3.2 Class objects

    Two operations

    • Attribute references
      such as:
    class MyClass:
        """A simple example class"""
        i = 12345
    
        def f(self):
            return 'hello world'
    

    MyClass.i and MyClass.f

    • Instantiation
    x = MyClass()
    >>> class Complex:
    ...     def __init__(self, realpart, imagpart):
    ...         self.r = realpart
    ...         self.i = imagpart
    ...
    >>> x = Complex(3.0, -4.5)
    >>> x.r, x.i
    (3.0, -4.5)
    

    9.3.3 Instance Objects

    two attribute references

    • data attributes 按照上面代码的定义可以直接这样写:
    x.counter = 1
    while x.counter < 10:
        x.counter = x.counter * 2
    print(x.counter)
    del x.counter
    
    • methods
      a method is a function that "belongs to" an object
      x.f is method reference bu MyClass.f is a function, But x.f is not the same thing as MyClass.f — it is a method object, not a function object.
      即x.f代表是类的成员变量,而不是函数对象

    9.3.4 Method Objects

    xf = x.f
    while True:
        print(xf())
    

    call x.f() is exactly equivalent to MyClass.f(x)
    When a non-data attribute of an instance is referenced, the instance’s class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list
    当一个非数据的属性被referenced的时候,会搜索类里面的属性,如果找到同名类属性,那么就创建一个方法对象(打包当前的对象和函数对象在一个抽象的对象里),当调用的时候再构建一个新的参数列表 然后用函数对象调用

    9.3.5 Class and Instance Variables

    Instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class.
    Shared data can have possibly surprising effects with involving mutable objects such as lists and dictionaries.

    9.4 Random Remarks

    Data attributes override method attributes:Possible conventions include capitalizing method names, prefixing data attribute names with a small unique string (perhaps just an underscore), or using verbs for methods and nouns for data attributes
    我一般用第三种来区分成员或者方法
    Any function object that is a class attribute defines a method for instances of that class.
    类函数属性同时定义了该函数的属性
    Each value is an object, and therefore has a class (also called its type). It is stored as object.class

    9.5 Inheritance

    class DerivedClassName(BaseClassName):
        <statement-1>
        .
        .
        .
        <statement-N>
    
    class C(B):
        def method(self, arg):
            super().method(arg)    # This does the same thing as:
                                   # super(C, self).method(arg)
    
    • Execution of a derived class definition proceeds the same as for a base class. When the class object is constructed, the base class is remembered. This is used for resolving attribute references: if a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class.
      先在子类找相应的属性,找不到再到父类去找
    • For C++ programmers: all methods in Python are effectively virtual
      A method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it
      基类调用基类方法会最终调用被重载的基类方法
    • An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name.
      just call BaseClassName.methodname(self, arguments)
      扩展而不是完全替换用 BaseClassName.methodname(self, arguments)
    • python 两个内置方法
      Use isinstance() to check an instance’s type: isinstance(obj, int) will be True only if obj.__class__ is int or some class derived from int.
      Use issubclass() to check class inheritance: issubclass(bool, int) is Truesince bool is a subclass of int. However, issubclass(float, int) is Falsesince float is not a subclass of int.

    9.5.1 Multiple Inheritance

    Simply, you can think of the search for attributes inherited from a parent class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy.
    不同的基类继承同一个基类的基类,只调用一次
    But more complex, the method resolution order changes dynamically to support cooperative calls to super()
    复杂一点用super可以动态调用
    To keep the base classes from being accessed more than once, the dynamic algorithm linearizes the search order in a way that preserves the left-to-right ordering specified in each class, that calls each parent only once.
    https://www.python.org/download/releases/2.3/mro/
    https://blog.csdn.net/qijiqiguai/article/details/77341170
    https://blog.csdn.net/lb786984530/article/details/81192721
    多继承初始化方案
    多继承初始化方案
    https://stackoverflow.com/questions/34884567/python-multiple-inheritance-passing-arguments-to-constructors-using-super
    super来调用new
    https://stackoverflow.com/questions/9056955/what-does-super-in-new
    https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods
    new的具体用法
    https://howto.lintel.in/python-new-magic-method-explained/

    官方文档
    https://docs.python.org/2/library/functions.html#super

    关于initnew,即如果调用了new返回了新的instance,就调用init ,否则不调用
    https://docs.python.org/2/reference/datamodel.html

    9.6 Private Variables

    • A convention is: a name prefixed with an underscore should be treated as a non-public part
    • Name mangling: Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls.
    class Mapping:
        def __init__(self, iterable):
            self.items_list = []
            self.__update(iterable)
    
        def update(self, iterable):
            for item in iterable:
                self.items_list.append(item)
    
        __update = update   # private copy of original update() method
    
    class MappingSubclass(Mapping):
    
        def update(self, keys, values):
            # provides new signature for update()
            # but does not break __init__()
            for item in zip(keys, values):
                self.items_list.append(item)
    

    即 就是想让父类的init method调用父类的update method,而不被子类override
    https://www.zhihu.com/question/30497826
    https://blog.csdn.net/g11d111/article/details/71367649

    例外:exec() 和 eval() 和其他限制
    https://stackoverflow.com/questions/38606804/private-variables-and-class-local-references

    9.7 Odds and Ends

    • Expects a particular abstract data type can be passed a class.
    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
    
    • Instance method have attributes: m.self and m.func

    9.8 Iterators

    9.9 Generators

    9.10 Generator Expressions

    相关文章

      网友评论

        本文标题:The Python Tutorial - C9 Classes

        本文链接:https://www.haomeiwen.com/subject/pteolctx.html