一以贯之

内置函数双下方法

__str__
__repr__
__len__
__format__
__new__
__item__
__
 
 
 
__str__和__repr__
改变对象的字符串显示
 
当需要使用__str__的场景时找不到就找__repr__
当需要使用__repr__的场景时找不到__repr__的时候就找父类的repr

 

format格式化输出

 

 

#_*_coding:utf-8_*_
format_dict={
    'nat':'{obj.name}-{obj.addr}-{obj.type}',#学校名-学校地址-学校类型
    'tna':'{obj.type}:{obj.name}:{obj.addr}',#学校类型:学校名:学校地址
    'tan':'{obj.type}/{obj.addr}/{obj.name}',#学校类型/学校地址/学校名}
class School:
    def __init__(self,name,addr,type):
        self.name=name
        self.addr=addr
        self.type=type

    def __repr__(self):
        return 'School(%s,%s)' %(self.name,self.addr)
    def __str__(self):
        return '(%s,%s)' %(self.name,self.addr)

    def __format__(self, format_spec):
        # if format_spec
        if not format_spec or format_spec not in format_dict:
            format_spec='nat'
        fmt=format_dict[format_spec]
        return fmt.format(obj=self)

s1=School('oldboy1','北京','私立')
print('from repr: ',repr(s1))
print('from str: ',str(s1))
print(s1)

'''
str函数或者print函数--->obj.__str__()
repr或者交互式解释器--->obj.__repr__()
如果__str__没有被定义,那么就会使用__repr__来代替输出
注意:这俩方法的返回值必须是字符串,否则抛出异常
'''
print(format(s1,'nat'))
print(format(s1,'tna'))
print(format(s1,'tan'))
print(format(s1,'asfdasdffd'))

 

 

__del__
 
析构方法:  在删除一个对象的时候做一些首尾工作
析构方法,当对象在内存中被释放时,自动触发执行。
 
注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。

 

class Foo:

    def __del__(self):
        print('执行我啦')

f1=Foo()
del f1
print('------->')

#输出结果执行我啦
------->
 
 
item系列
__getitem__
__setitem__
__delitem__
 
 
class Foo:
    def __init__(self,name):
        self.name=name

    def __getitem__(self, item):
        print(self.__dict__[item])
        return 1  不写默认return  none

    def __setitem__(self, key, value):
        self.__dict__[key]=value

    def __delitem__(self, key):
        print('del obj[key]时,我执行')
        self.__dict__.pop(key)

    def __delattr__(self, item):
        print('del obj.key时,我执行')
        self.__dict__.pop(item)

f1=Foo('sb')
print(f1.__dict__) #{'name': 'sb'}

f1['age']=18
print(f1['age']) #18 还有一个return值 1
f1['age1']=19

del f1.age1 #del obj.key时,我执行
del f1['age'] #del obj[key]时,我执行
#
f1['name']='alex'
print(f1.__dict__) #{'name': 'alex'}

 

 
__new__
 
 
构造方法
实例化的时候
         创造对象的过程  __new__
         __init__ 初始化
先执行__new__然后执行__init__
 
class A:
    def __init__(self):
        self.x = 1
        print('in init function')
    def __new__(cls, *args, **kwargs):
        print('in new function')
        return object.__new__(A, *args, **kwargs)

a = A()
print(a.x)

 

 
class B:
    __instance = None
    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            obj = object.__new__(cls)
            cls.__instance = obj
        return cls.__instance
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def func(self):
        print(self.name)

a = B('alex',80)
b = B('egon',20)
print(a)        #<__main__.B object at 0x00000213AAA3B7F0>
print(b)        #<__main__.B object at 0x00000213AAA3B7F0>
print(a.name)  #egon
print(b.name)    #egon

 

 
单例模式
 
class Singleton:
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            cls._instance = object.__new__(cls, *args, **kw)
    return cls._instance

one = Singleton()
two = Singleton()

two.a = 3
print(one.a)
# 3
# one和two完全相同,可以用id(), ==, is检测
print(id(one))
# 29097904
print(id(two))
# 29097904
print(one == two)
# True
print(one is two)

 

__call__
 
对象后面加括号,触发执行。
注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
 
一个对象是否可调用 完全取决于这个对象对应的类是否实现了__call__
 
class Foo:

    def __init__(self):
        pass
    def __call__(self, *args, **kwargs):

        print('__call__')


obj = Foo() # 执行 __init__
obj() # 执行 __call__

 

 

__len__

class A:
    def __init__(self):
        self.a = 1
        self.b = 2

    def __len__(self):
        return len(self.__dict__)
a = A()
print(len(a))

 

__hash__
 
 
class A:
    def __init__(self):
        self.a = 1
        self.b = 2

    def __hash__(self):
        return hash(str(self.a)+str(self.b))
a = A()
print(hash(a))

 

__eq__
 
== 是由__eq__的返回值来决定的
class A:
    def __init__(self):
        self.a = 1
        self.b = 2

    def __eq__(self,obj):
        if self.a == obj.a and self.b == obj.b:
            return True
a = A()
b = A()
print(a == b)

 

 
 
 
 
 
 
 

 

posted on 2019-04-24 17:22  凡夫or俗子  阅读(160)  评论(0)    收藏  举报