Object-oriented basis of many states

Polymorphism

concept:

A thing with a variety of different forms

For example: water, gas liquid solid

Hornet: car people, cars, airplanes

The official explanation: a plurality of objects of different classes can respond to the same method, different results

First emphasized polymorphism is not a special syntax, but a state, characteristics (both in response to a plurality of different objects may be the same method, different results)

Both have the plurality of objects using the same method,

benefit:

For users, greatly reducing the difficulty of use

Before we write the USB interface, the mouse under the keyboard, they are multi-state

Multi-state:

Interface type ducks abstract class can have write polymorphic code is the simplest type of duck

Case:

"""
要管理 鸡 鸭 鹅
如何能够最方便的 管理,就是我说同一句话,他们都能理解
既它们拥有相同的方法

"""
class JI:
    def bark(self):
        print("哥哥哥")

    def spawn(self):
        print("下鸡蛋..")

class Duck:
    def bark(self):
        print("嘎嘎嘎")

    def spawn(self):
        print("下鸭蛋")

class E:
    def bark(self):
        print("饿饿饿....")

    def spawn(self):
        print("下鹅蛋..")

j = JI()
y = Duck()
e = E()

def mange(obj):
    obj.spawn()


mange(j)
mange(y)
mange(e)


# python中到处都有多态  
a = 10
b = "10"
c = [10]

print(type(a))
print(type(b))
print(type(c))

isinstance

Determining whether an object is an instance of a class

To determine a parameter object

To determine the type of the parameter 2

issubclass

Determining whether a class is a subclass of another class

The first parameter subclass

Two parameters is the parent class

str

__str__  会在对象被转换为字符串时,转换的结果就是这个函数的返回值 
使用场景:我们可以利用该函数来自定义,对象的是打印格式

of the

执行时机: 手动删除对象时立马执行,或是程序运行结束时也会自动执行 
使用场景:当你的对象在使用过程中,打开了不属于解释器的资源:例如文件,网络端口 
        
# del使用案例

# class FileTool:
#     """该类用于简化文件的读写操作 """
# 
#     def __init__(self,path):
#         self.file = open(path,"rt",encoding="utf-8")
#         self.a = 100
# 
#     def read(self):
#         return self.file.read()
# 
#     # 在这里可以确定一个事,这个对象肯定不使用了 所以可以放心的关闭问文件了
#     def __del__(self):
#         self.file.close()
# 
# 
# tool = FileTool("a.txt")
# print(tool.read())

call

执行时机:在调用对象时自动执行,(既对象加括号)

test:

#call 的执行时机
class A:
    def __call__(self, *args, **kwargs):
        print("call run")
        print(args)
        print(kwargs)

a = A()
a(1,a=100)

slots

该属性是一个类属性,用于优化对象内存占用
优化的原理,将原本不固定的属性数量,变得固定了
这样的解释器就不会为这个对象创建名称空间,所以__dict__也没了  
从而达到减少内存开销的效果 

另外当类中出现了slots时将导致这个类的对象无法在添加新的属性  
# slots的使用
class Person:

    __slots__ = ["name"]
    def __init__(self,name):
        self.name = name

p =  Person("jck")

# 查看内存占用
# print(sys.getsizeof(p))
# p.age = 20 # 无法添加

# dict 没有了
print(p.__dict__)

getattr setattr delattr

getattr 用点访问属性的时如果属性不存在时执行
setattr 用点设置属性时
delattr 用del 对象.属性  删除属性时 执行


这几个函数反映了 python解释器是如何实现 用点来访问属性 

getattribute 该函数也是用来获取属性
在获取属性时如果存在getattribute则先执行该函数,如果没有拿到属性则继续调用 getattr函数,如果拿到了则直接返回  

.

[] The real principle

GetItem setitem Delite

Any symbol will be interpreted as a special meaning interpreter, for example. [] ()

getitem 当你用中括号去获取属性时 执行
setitem  当你用中括号去设置属性时 执行
delitem 当你用中括号去删除属性时 执行

Operator overloading

When we use a certain symbol, Python interpreter will be a symbol definition for the meaning of, and call the corresponding handler, when we need to custom objects comparison rule can cover greater than or equal in subclasses series method....

Case:

Originally custom object can not be used directly greater than less than to compare, we can customize the operator to achieve, also make custom objects support comparison operators

class Student(object):
    def __init__(self,name,height,age):
        self.name = name
        self.height = height
        self.age = age

    def __gt__(self, other):
        # print(self)
        # print(other)
        # print("__gt__")
        return self.height > other.height
    
    def __lt__(self, other):
        return self.height < other.height

    def __eq__(self, other):
        if self.name == other.name and  self.age == other.age and self.height == other.height:
            return True
        return False

stu1 = Student("jack",180,28)
stu2 = Student("jack",180,28)
# print(stu1 < stu2)
print(stu1 == stu2)

In the above code, other refers to the object involved in another comparison,

Any one of those above and below can, if different symbol interpreter automatically switching the position of two objects

Iterator protocol

迭代器是指具有__iter__和__next__的对象
我们可以为对象增加这两个方法来让对象变成一个迭代器 

Case:

class MyRange:

    def __init__(self,start,end,step):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        return self

    def __next__(self):
        a = self.start
        self.start += self.step
        if a < self.end:
            return a
        else:
            raise StopIteration
            
for i in MyRange(1,10,2):
    print(i)
   

Context Management

Context context

This concept belongs to language learning, referring to the meaning of a passage, to refer to the current scene, both context

In python, the context can be understood as a section of code, a range of, for example, open files with open only valid in this context

The method involves the two:

enter

That enter context, (entered the scene a)

exit

It means exit context, (the exit a scene)

When performing with the statement, it will be executed first enter,

When the code is completed execution exit, or code encounters an exception will perform exit immediately, and pass an error message

Contains type of error. The error message Error tracking information

note:

enter 函数应该返回对象自己 
exit函数 可以有返回值,是一个bool类型,用于表示异常是否被处理,仅在上下文中出现异常有用
如果为True 则意味着,异常以及被处理了 
False,异常未被处理,程序将中断报错

Guess you like

Origin www.cnblogs.com/linxidong/p/11265695.html