094 built-in method

A built-in method

  1. __init__ is called automatically when the object is instantiated

  2. __str_ : If you do not rewrite __str _ Print Print will print out the memory address, if rewritten, it will print out what you want
  3. __repr__ similar with str, direct write the variable name in an interactive command, execute __repr__

  • __str__

    1.不写__str__
    class Foo:
        def __init__(self,name):
            self.name=name
        # def __str__(self):
        #     return '['+self.name+']'
    
    f=Foo('nick')
    print(f.__str__())

    <main.Foo object at 0x00000201444E77F0>

    2.写__str__
    class Foo:
        def __init__(self,name):
            self.name=name
        def __str__(self):
            return '['+self.name+']'
    
    f=Foo('xichen')
    print(f.__str__())

    [Xichen]

    l=[1,2,3]
    # #本质也是调用list的__str__方法
    print(l)

    [1, 2, 3]

1.__setattr__

  • Add / modify attributes will trigger its execution
  • If you assign attributes to objects, once to get any, will enter into __setattr__
class Foo:
    def __init__(self,name):
        self.name=name
        
    def __setattr__(self, key, value):
        print('对象没有这个属性')
1.原来字典使用方式dict
dic = dict(name='xichen',age=18)
print(dic)
print(dic ['name'])

{ 'name': 'xichen', 'Age':} 18 is
xichen

2.写一个类继承字典,让它可以 .取值,可以中括号取值
class Mydict(dict): # 继承dic这个类
    def __init__(self,**kwargs):
       
        super().__init__(**kwargs)

    def __getattr__(self, item):
      
        print(item)

        return self[item]
    def __setattr__(self, key, value):
        self[key]=value

        
        
di=Mydict(name='xichen',age=18)
print(di['name'])
print(di.name)
di.sex='male'
di['sex']='male'

di.age=18
print(di.age)

xichen
xichen

18

2.__getattr__

  • Only call the property at the point of use and the property does not exist when will trigger
  • If you go to fetch the object attributes, once to get any, will enter into __getattr__
class Foo:
    def __init__(self,name):
        self.name=name
    def __getattr__(self, item):
        return '没有这个字段'
    
f = Foo('xichen')
print(f.age)

Without this field

3.__delattr__

  • Delete property when the trigger
  • If the attribute deleted object, will enter __delattr__
class Foo:
    def __init__(self,name):
        self.name=name
        
    def __delattr__(self,item):
        self.__dict__.pop(item)
        print('删除成功')
        
        
del f.name
print(f.__dict__)

Successfully deleted
{ 'age': 18}

4 .__ item__ series

  • When the object by [] brackets value assignment, remove the value of calls
class Foo:
    def __init__(self, name):
        self.name = name
    def __getitem__(self, item):
        name=getattr(self,item)
        # print(name)
        # print(self.__dict__[item])
        return name
        # return self.__dict__[item]
    def __setitem__(self, key, value):
        print('obj[key]=lqz赋值时,执行我')
        self.__dict__[key] = value
    def __delitem__(self, key):
        print('del obj[key]时,执行我')
        self.__dict__.pop(key)
f=Foo('xichen')
print(f['name'])

xichen

  • __setitem__
f['age'] = 18
print(f['age'])
print(f.__dict__)

obj [key] = lqz assignment when performing I
18 is
{ 'name': 'xichen', 'Age':} 18 is

  • __delitem__
del f['age']
print(f.__dict__)

When del obj [key], do I
{ 'name': 'xichen' }

5 .__ call__: Object brackets will call it

class Foo:
    def __call__(self):
        print('调用我 !')

f=Foo()
f()

Call me!

6 .__ enter__ and __exit__

  • Essentially, the context manager
  • Is what we use to open the file with open when it is triggered __enter__, help us to open the file
  • When the system detects that we are the top grid write had actually been triggered __exit__, so help us to automatically release resources
with open('path','r') as f:
    pass

Guess you like

Origin www.cnblogs.com/xichenHome/p/11448722.html