内置方法

阅读目录:

__new__  

构造方法,   提供了一个类实例化对象的时候所需要的内存空间

实例化 的时候会触发这种方法

class Dog(object):
     def __new__(cls, *args, **kwargs):
         # dog_obj = object.__new__(cls)   #调用父类的__new 方法
         dog_obj = super().__new__(cls)
        return dog_obj
     def __init__(self,name,age):
        self.name = name
        self.age = age

wc = Dog('旺财',2)
print(wc.name)

单例模式

class Teacher:
     flag = None
     def __new__(cls, *args, **kwargs):
         if cls.flag is None:            
             cls.flag = object.__new__(cls)    # 这一句话只能走一次
         return cls.flag            # 此处返回的是object.__new__(cls)  
     def __init__(self,name):
         self.name = name

 zhangsan = Teacher('张三')
 lisi = Teacher('李四')
 wangwu = Teacher('王五')
 print(zhansan.name)
 print(wangwu.name)
执行结果:
王五 因为用的都是同一块对象空间,所以会产生覆盖,以最后一个值为准
王五
cls.flag =  self =  zhangsan = lisi= wangwu = <__main__.Teacher object at 0x000001D6B8169400>
import time 
class A:
    from threading import Lock
    lock = Lock()
    __instance = None
    def __new__(cls,*args,*kwargs):
        with cls.lock:
            if cls.__instance ==None:
                time.sleep(0.1)
                cls.__instance = object.__new__(cls)
        return cls.__instance

def func():
    a1 = A()
    print(a1)

import threading
threading.Thread(target = func).start()
threading.Thread(target = func).start()

 

__init__  

初始化方法

实例化  的时候会触发

__call__

对象() 的时候进行触发

class Student():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __call__(self, *args, **kwargs):
        print('调用我啦')
alex = Student('alex',83)
alex()

执行结果:调用我啦

__del__   

析构方法\对象删除之前的收尾工作

del 对象 的时候进行触发

class Teacher:
    def __init__(self,name):
        self.name = name
    def __del__(self):
        print('执行我啦')

zhangsan = Teacher('zhangsan')
print('hahaha')
del zhangsan   #执行del 对象的时候 触发__del__,在真正的删除alex对象之前,执行的方法__del__

# 如果我们自己不删除alex,那么在程序的执行过程中或者最后,垃圾回收机制会替你执行del alex
# 1.del zhangsan
# 2.执行__del__
# 3.删除zhangsan
class File(object):
    def __init__(self,file_name):
        self.f = open('file_name')

    def read(self):
        self.f.read(1024)

    def  __del__(self):   # 对象使用的一些操作系统的资源的归还工作/收尾工作
        self.f.close()
my_f = File()
my_f.read()

__str__

让一个对象的显示更加清晰

以下三种进行触发:

  • print(对象)
  • str(对象)
  • '%s'%对象
class Course:
    def __init__(self,name,price,period,teacher):
        self.name = name
        self.price = price
        self.period = period
        self.teacher = teacher
    def __str__(self):  # 必须有返回值,必须返回一个str类型
        return '%s,%s,%s,%s'%(self.name,self.price,self.period,self.teacher)
python = Course('python',19800,'6 months','张三')
linux = Course('linux',16800,'5 months','李四')
print(python) print(str(python)) print('课程展示 : %s'%python)
执行结果:

python,19800,6 months,张三
python,19800,6 months,张三
课程展示 : python,19800,6 months,张三

__repr__  

是str方法的备胎 (有str调用str,没有str走repr)

以下两种方式进行触发:

  • repr() 
  • '%r'%对象
class Course:
    def __init__(self,name,price,period,teacher):
        self.name = name
        self.price = price
        self.period = period
        self.teacher = teacher
    def __repr__(self):  # 必须有返回值,必须返回一个str类型
        return 'repr --> : %s,%s,%s,%s'%(self.name,self.price,self.period,self.teacher)
    # def __str__(self):  # 必须有返回值,必须返回一个str类型
    #     return 'str --> : %s,%s,%s,%s'%(self.name,self.price,self.period,self.teacher)
python = Course('python',19800,'6 months','baoyuan')
linux = Course('linux',16800,'5 months','张三')
print('%r'%python)
print('%s'%python)
print(str(python))
print(repr(python))
执行结果:

repr --> : python,19800,6 months,baoyuan
repr --> : python,19800,6 months,baoyuan
repr --> : python,19800,6 months,baoyuan
repr --> : python,19800,6 months,baoyuan

__len__

len(对象)进行触发

class Ruler:
    def __init__(self,price,length,jingdu):
        self.length = length
        self.price = price
        self.jingdu = jingdu
    def __len__(self):
        return self.length
stu_ruler = Ruler(2.5,15,0.1)
print(len(stu_ruler))

item系列

__getitem__

__setitem__

__delitem__

class Course:
    def __init__(self,name,price,period,teacher):
        self.name = name
        self.price = price
        self.period = period
        self.teacher = teacher
    def __len__(self):
        return len(self.__dict__)
    def __getitem__(self,item):
        return self.__dict__[item]
    def __setitem__(self, key, value):
        self.__dict__[key] = value
    def __delitem__(self, key):
        self.__dict__.pop(key)
python = Course('python',19800,'6 months','baoyuan')
print(python.name)
print(python['name'])   # ==> 调用getitem
print(python['price'])   # ==> 调用getitem
python['name'] = 'python2.0'   # ==> setitem
print(python.name)
del python['name']    # ==>delitem
print(python.__dict__)

__eq__

== 触发 __eq__

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

s1 = Student('贾卫东',20)
s2 = Student('贾卫东',20)
print(s1 == s2)   # s1.__eq__(s2)
print(s1 is s2)   # s1.__eq__(s2)

执行结果:

True
False

 

posted @ 2019-02-07 16:29  小萍瓶盖儿  阅读(129)  评论(0编辑  收藏  举报