Thoroughly get to know Python data members and member methods

First, the data members (attributes)

Data member can be divided into two categories: data belonging to the object data members and member of the class.

  • Belonging to the object data members typically __init __ () defined in the configuration method, of course, also be defined in other members of the process, when defining and accessing data members in the example of the method to self as a prefix, different objects of the same class (Example ) simultaneously and the data members;
  • Belonging to the class data members are shared by all objects in that class, does not belong to any object, when defining the data members of this class does not define any member of the general method.

Second, the member method

Python class member methods can be divided into public methods, private methods, static methods, class methods these types.

  • Public methods, private methods generally refers to an instance method belongs to the object, the name of private methods in two underscores "__" began, and abstract method is generally defined in an abstract class and derived class must re-implement the requirements. Each object has its own methods of public and private methods in these two types of methods can be accessed by members belong to classes and objects.

  • Public methods invoked through direct object name "object name. Public method (<arguments>)" private method can not directly call the object name, can be called only by self prefix method or in other examples by a special externally forms transfer.

  • All the Examples of the method must have at least one called self parameter and must be the first process parameter (if there are multiple parameter words), the self parameter represents the current object.

  • Need to be self prefixed to access instance members in an instance method, but externally by object name does not need to pass this argument when you call the object methods.

  • If the outside through the class name public methods belonging to the object invocation, the need for an explicit method of self parameter passing an object name, which is used to explicitly specify the members to access the object.

  • Static methods and class methods are available through the class name and the object name to call, but can not access the members belonging to the object directly, can access only the members of the class.

  • Static methods and methods do not belong to any class instance, not bound to any instance, of course, does not depend on any state of the instance, it can be reduced as compared with the example of the method a lot of overhead.

  • The method generally abbreviated class cls as class methods of the class represented by the first parameter itself, when calling the method does not require the class values for parameter passing, static methods can not receive any parameters.

>>> class Root:
    __total = 0
    def __init__(self, v):    #构造方法
        self.__value = v
        Root.__total += 1

    def show(self):           #普通实例方法
        print('self.__value:', self.__value)
        print('Root.__total:', Root.__total)

    @classmethod              #修饰器,声明类方法
    def classShowTotal(cls):  #类方法
        print(cls.__total)

    @staticmethod             #修饰器,声明静态方法
    def staticShowTotal():    #静态方法
        print(Root.__total)
        
>>> r = Root(3)
>>> r.classShowTotal()              #通过对象来调用类方法
1
>>> r.staticShowTotal()             #通过对象来调用静态方法
1
>>> r.show()
self.__value: 3
Root.__total: 1
>>> rr = Root(5)
>>> Root.classShowTotal()           #通过类名调用类方法
2
>>> Root.staticShowTotal()          #通过类名调用静态方法
2

>>> Root.show()    #试图通过类名直接调用实例方法,失败
TypeError: unbound method show() must be called with Root instance as first argument (got nothing instead)
>>> Root.show(r)   #但是可以通过这种方法来调用方法并访问实例成员
self.__value: 3
Root.__total: 2
>>> Root.show(rr)  #通过类名调用实例方法时为self参数显式传递对象名
self.__value: 5
Root.__total: 2

Third, the method attribute

  • Use @porperty decorator decoration method, the program can function "as a" property access, thereby providing a more user-friendly access.

Read-only attribute:

>>> class Test:
	    def __init__(self, value):
		self.__value = value

	    @property
	    def value(self):               #只读,无法修改和删除
		return self.__value
>>> t = Test(3)
>>> t.value
3
>>> t.value = 5                        #只读属性不允许修改值
AttributeError: can't set attribute
>>> t.v=5                              #动态增加新成员
>>> t.v
5
>>> del t.v                            #动态删除成员
>>> del t.value                        #试图删除对象属性,失败
AttributeError: can't delete attribute
>>> t.value
3

Readable, writable property:

>>> class Test:
    def __init__(self, value):
        self.__value = value	

    def __get(self):
        return self.__value

    def __set(self, v):
        self.__value = v
    value = property(__get, __set)

    def show(self):
        print(self.__value)
>>> t = Test(3)
>>> t.value      #允许读取属性值
3
>>> t.value = 5  #允许修改属性值
>>> t.value
5
>>> t.show()     #属性对应的私有变量也得到了相应的修改
5
>>> del t.value  #试图删除属性,失败
AttributeError: can't delete attribute

Read, modify, delete properties:

>>> class Test:
    def __init__(self, value):
        self.__value = value

    def __get(self):
        return self.__value

    def __set(self, v):
        self.__value = v

    def __del(self):
        del self.__value

    value = property(__get, __set, __del)

    def show(self):
        print(self.__value)
>>> t = Test(3)
>>> t.show()
3
>>> t.value
3
>>> t.value = 5
>>> t.show()
5
>>> t.value
5
>>> del t.value            #删除属性
>>> t.value                #对应的私有数据成员已删除
AttributeError: 'Test' object has no attribute '_Test__value'
>>> t.show()
AttributeError: 'Test' object has no attribute '_Test__value'
>>> t.value = 1            #为对象动态增加属性和对应的私有数据成员
>>> t.show()
1
>>> t.value
1
Published 115 original articles · won praise 445 · views 50000 +

Guess you like

Origin blog.csdn.net/zag666/article/details/105209782