原理和语言

The Python Tutorial - C9 Classes

2019-07-24  本文已影响0人  左心Chris

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

9.2.1 scopes and namespaces example

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

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

9.3 First look at classes

9.3.1 class definition syntax

class ClassName:
  <statement>
  <statement>

9.3.2 Class objects

Two operations

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

MyClass.i and MyClass.f

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

x.counter = 1
while x.counter < 10:
    x.counter = x.counter * 2
print(x.counter)
del x.counter

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)

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

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

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 Iterators

9.9 Generators

9.10 Generator Expressions

上一篇下一篇

猜你喜欢

热点阅读