Python Learning Notes (v) OOP

Source: Internet
Author: User

Module

Use the module import 模块名 . Some only import a class or function of a module, using the from 模块名 import 函数或类名 implementation. To avoid module name collisions. Python introduces a way to organize modules by folder, called a package.

The name of the b.py module under the A folder is a.b . A file must be in the folder a __ini__.py . Even if the contents of the file are empty. Otherwise a will become a normal folder.

Standard module file Template:

#!/usr/bin/env python3# -*- coding: utf-8 -*-‘a test module‘#不论什么模块的第一个字符串都被视为模块的文档凝视‘Your Name‘...def f():...if‘__main__‘:  #从其它地方导入模块,if不会通过。因此能够用来在命令行下进行測试    f()
    • The non-public function prefix in the module _ . Such asdef _private_1():
    • Special variables that can be directly quoted are generally __argname__ represented by the two underscores in front and back. Custom public functions or variables are generally used in normal form def f , without such an underscore.
    • It is important to note that. Python does not have a way to completely restrict access to private functions or variables. So this has to be self-conscious.

Third-party modules can be installed using PIP pip install numpy . It will be downloaded and installed on its own initiative from the official Python site.

You can also download it yourself and install it later.

Object-Oriented Programming class syntax
class Student(object):    pass

objectis the default parent class name. The creation of the instance is used tom = Student() . As a dynamic language, Python supports the freedom to give Tom new properties outside of the binding class tom.name = ‘Tom‘ .

Suppose you have properties that you need to bind when you create an instance. Typically written in a function in a class __ini__ :

def __ini__(self, arg1, arg2):    ...    ...

__ini__The first argument is always self and will be passed on by itself.

With such a __ini__ . arg1the input and the parameters are required when the instance is created arg2 . __arg1the two preceding underscores indicate that this is a private property and cannot be interviewed externally.

Duck type: Just look like a duck. Run like a duck, you can be seen as a duck.

The dynamic nature of Python is now inherited. Suppose there is a method in a function that calls a class, and only the object that is passed in can be run, regardless of whether the object is an instance of that class or subclass of that class.

Get object Information
    • The information that gets the object can use type (), which is assumed at the same time import types . can also be used type(对象) == types.type模块中的常量函数类型 to infer whether an object is a type of detailed function.

    • isinstance(对象,类)The inferred method assumes that the object is the parent of the class in the parameter and also returns TRUE. Isinstance can be used for basic types inferred by type, and the second can be a list. Just to satisfy is one of the elements returns True.

    • Dir () is able to return all the properties and methods of an object

    • Can be used to hasattr(obj, ‘arg‘) get obj If there is an arg attribute or method, getattr(obj, ‘arg‘) return a property or method, set a setattr(obj, ‘arg‘, value) property or method (not add it directly) when the object details are not known

Object-oriented advanced programming use __slots__

Because Python is a dynamic language. It is therefore possible to bind properties or methods arbitrarily for classes, instances. The binding method is used from types import MethodType to s.f = MethodType(f, s) bind the method F to the class or instance S. At the same time, be aware that the first parameter of F is bound by self talent.

Assuming that you want to restrict the properties of an instance, you need to define a special variable to define the class to __slots__ = (‘name1‘,‘name2‘) qualify the property name of the instance binding to be only name1 or name2.

Analysis:

from types import MethodTypeclass Student(object): __slots__ = (‘name‘, ‘sex‘, ‘set_name‘, ‘set_grade‘)#同意绑定的在下文中称为内方法和内属性。

#内方法中绑定内属性 def set_name : self.name = Name #内方法中绑定外属性 # def set_grade (self, grade) : self.grade = Grade #外方法中绑定外属性 # def set_score (self, score) : self.score = Score #外方法中绑定内属性 # def set_sex (self, sex) : self.sex = Sextom = Student () Jane = Student ()

(1) Bind attributes to an instance:

‘Tom‘    #正确。name是内属性98    #错误,grade是外属性。不能绑定print(jane.name)    #错误,未定义实例jane的name#第三句可见实例绑定的属性仅仅算各个实例自己的

(2) To bind a property to a class:

Student.name = ‘name‘    #内属性能够绑定0    #外属性也能够绑定,可见__slots__仅仅作用于实例tom.name = ‘Tom‘    #错误。可见通过这样的方法绑定的属性到实例中为仅仅读print(jane.name)    #输出为name

(3) Bind method to instance:

tom.set_name = MethodType(set_name, tom)    #内方法,当中绑定内属性tom.set_grade = MethodType(set_name, tom)    #内方法。当中绑定外属性。调用方法时会报错tom.set_score = MethodType(set_score, tom)    #外方法。不可绑定tom.set_sex = MethodType(set_name, tom)    #外方法,不可绑定

(4) Binding methods to classes

 #绑定内方法  student.set_name = Methodtype (Set_name, Student) Tom.name =  ' Tom '  print  (jane.name)  #报错, visible before invoking a property within a method binding. "instance. Attribute =" In fact back to the first discrimination case  Tom.set_name ( ' Tom ' ) jane.set_name ( ' Jane ' )  #调用内方法 to bind the inner property to the class  Tom.name =  Tom '   #报错. The previous sentence is visible in the same property as the binding (3). Just read. 

仅仅能通过类方法改动print(jane.name)print(tom.name) #输出也是Jane,可见通过类方法改动的属性是类属性,各实例的相应属性都是最后一次调用类方法之后的属性值#绑定内方法,当中绑定外属性Student.set_grade = MethodType(set_grade, Student)tom.set_grade(4) #调用方法绑定了外属性tom.grade = 4 #类属性仅仅读。不可直接改动print(tom.grade) #实例拥有了外属性,只是是类属性,仅仅读,仅仅能通过类方法改动

The remaining two cases are no longer mentioned, because the __slots__ classes are not restricted, so no matter what methods and properties can be bound. Only the properties that are bound by the calling method are read only, and can only be changed by invoking the method, and cannot be directly used in the instance . by the above analysis, such as the following:

__slots__Restrict only the method or property binding of an instance, without restricting the class.

Methods and properties that are bound to a class can be called in an instance, but the class property is read-only in the instance, whose value is the last Call method or 类.属性= the result of the assignment, and cannot be changed in the instance 实例.属性= .

Using @property

When the property needs to be changed. To be able to check the parameters, the method is generally called to set the property value.

But that would be a bit of a hassle.

This is when the @property decorator works.

@propertydef name(self):    return self._name@name.setter #假设不用下面的部分,则name就变成了仅仅读属性def name(self,value):    ...类型检查等    self._name = value

Note that attributes _name must be underlined to differentiate properties and methods, otherwise the name becomes a method. The code above is recursive. will be reported recursive number overflow error

Multiple inheritance

Assuming that more than one inherited parent class has the same method, whichever is the first, the method of the following parent class will not work.

Custom Classes

__slots__There are two underlined variables or functions at both ends of this type that have a special purpose, so you can customize the class by defining such objects.

__str__(self): When run print(类) , the program prints out properties and memory addresses, assuming you want to print out specific content. You can define a __str__ method that outputs a specific content.

It is assumed that the class name output information is directly invoked without print. You need to define the __repr__() method. A simple definition method is a __repr__ = __str__ high-speed definition.

__iter__(self): If you want to iterate over a class, you need to define the __iter__ method return self . And then define a __next__(self) method to run the iteration in order to do things

__getitem__(self, n): Turns the class into a list that can be manipulated by the subscript element.

__getitem__returns the element value under. Suppose you want to implement features such as slicing. Further refinement of this function is also needed, such as inferring whether the incoming argument is a series of slice.

In the same way, the class is changed to be used like Dict __setitem__ . Use the __delitem__ delete element.

These methods turn the class into a list or dict "duck" so that the class can operate like a list or a dict.

__getattr__(self, attr): Returns a dynamic property or method.

The attr is inferred from the bottom of the function. thereby binding the specified property or method. The binding property returns the property value. The binding method returns a lambda function.

Assuming that there are no restrictions whatsoever, it is clear that any property or method can bind. When the assumption returns itself, a chained call is implemented. Use this to construct an SDK for different APIs. The following code implements the URL output of a GitHub API:

 class Chain(object):     def __init__(self, Path ="):Self._path = Path def __getattr__(self, path):        returnChain ('%s/%s '% (Self._path, path)) def __call__(self,name):        returnChain ('%s/:%s '% (Self._path, name)) def __str__(self):        return ' GET '+ Self._path Print (Chain (). Users (' Hermanncain '). Repos)#输出为GET/users/:hermanncain/repos

__call__(self): invokes the instance itself.

s()run when called __call__(self) . can also be used __call__(self, *args, **kw) to pass a number of parameters, the s(*args, *kw) contents of which are run when called. This blurs the bounds of the class and instance.

Enum class
from   Enum  import enum  Month = enum  ( ' Month ' , (, , Span class= "hljs-string" "Mar" , ,  ' May ' , ,  ' Jul ' , , class= hljs-string , , ) for  name, member in  month.__member__.items (): Print (name, , member,  ', ' , Member.value) 

value is the corresponding int value for the enumeration member, starting from 1 by default

There is also a custom enumeration class derived from Enum. The syntax is somewhat like the enumeration type in C + +:

from enum import Enum, unique@uniqueclass Weekday(Enum):    0    1    ...

@uniqueAdorners are used to check for repeated values.

There are several reference methods for members of an enumeration class:

print(Weekday.Sun)print(Weekday[‘Sun‘])print(Weekday(1))#以上的输出都是Weekday.Sunprint(Weekday.Sun.value)#输出0
Meta-class * use type()Create Class

The definition of functions and classes for dynamic languages is created dynamically at run time.

Write a a.py module. Defined in the module, class A and then in the main program, the module from a import A is loaded when the entire statement runs, the result is the dynamic creation of a class. type(A)The return value is type , type(A的实例) the return value is class ‘__main__‘.A .

However, type() it can also be used to dynamically create classes. In fact, when the Python interpreter encounters the class definition, it is also used to type() create the class dynamically:

...):    ...A = type(‘A‘, (object,), dict(af = f)

This creates a class on the fly A . The parent class is object (note that the multiple-inheritance parent class is placed inside tuple .) Suppose there is only one parent class, the tuple has only one element, and the comma is not limited. And there is a af method named.

metaclassMeta class *

Class is equivalent to an instance of a meta class. Metaclass is the most difficult and difficult-to-use magic code for Python-oriented objects. Generally not used

* This part of the content is skipped first, when used in accordance with instances to organize

Python Learning Notes (v) OOP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.