python中的类生命周期方法

__str__:面向用户,在本方法中定义了返回值后(必须是str),可以在使用实例时返回这个str

__repr__:面向开发人员,同上

import functools
class Mountion():def __call__(self,c):
        self.c=c
    def __str__(self):
        return str(self.__dict__)
    def __repr__(self):
        return str(id(self))
    def __init__(self,llk=0,height=0):
        self.__llk=llk
        self.height=height

如何输出str返回的str:直接输出print(str(p))

if __name__ == '__main__':
    a=Mountion()
    print(a)
    print(str(a))

如何输出repr:print(repr(p)),在命令行中直接输出p回车

if __name__ == '__main__':
    print(trpr(a))

在执行print(p)时,优先寻找执行__str__,如果没找到,然后寻找执行__repr__

__call__:当类中写了这个函数时:

执行实例时—---p(),相当于执行p这个实例的__call__方法

if __name__ == '__main__':
    a=Mountion()
    a(8)

此时实例a的实例属性有__llk=0,height=0,c=8

可以实现类似偏函数的功能--可以实现简洁的执行多个有部分相同参数的函数

如果__call__函数编变成这样

class Mountion():
    def __call__(self,c):
        print("本次的c值%s,height值%s",%(c,height))

main函数变成这样

if __name__ == '__main__':
    a=Mountion(height=999)
    a(1)
    a(2)
    a(3)

输出将变成

本次的c值1,height值999
本次的c值2,height值999
本次的c值3,height值999

类中的__call__函数能实现批量实例化吗?
估计不行,__call__函数在类中,而不是类外

__setattr__:设置self中的属性(变量)的值,通过更新__dict__字典,可以用来设置值的时候限制某些key拒绝写入或者改变写入时value的值或者类型等操作

另外

执行类时----Person(),优先执行__str__,其次执行__repr__,最后返回<__main__.Mountion object at 0x000002E075DF18B0>,而不是执行类的__call__方法

在执行print(Persion)时,会输出<class '__main__.Mountion'>,不会调用__str__和__rerp__

eval()函数可以执行一个字符串表达式,比如eval(“6+3”)

但是在b=Person()时会正常实例化

posted on 2021-01-26 22:41  JUNE鹦鹉学舌  阅读(203)  评论(0)    收藏  举报