Python trip on the 25th day (getattribute, item series, str, repr, format)

Today abused, and vowed to brush the question, the result was the title by friction on the floor, so keep up the good science, good practice it. After the weekend is really precious, content needs to have a lot of practice, today is really a profound experience every day, taking notes on this stuff above benefits, and forgot to double life flattered.

A supplement for reflection

# About the content of the supplement reflection 
# detail, said yesterday on __hasattr__ __setattr__ __delattr__ __getattr__ 
# yesterday focused on class and instance objects, we have tested the above functions, it can be used 
# so for the file if it can be used normally ? 
# Remember that everything is an object in Python, of course, wide file with the 
# test.py contents of the file: 
# DEF the Test (): 
#      Print ( 'the Hello Word') 
Import the Test AS test_obj
 Print (hasattr (test_obj, ' the Test ' ))    # returns True 
# here to prove all claims are subject 
# this role is mainly for time to develop more than one person at the same time can not wait for the results of others, you can first start 
# such test file is not defined in the add method 
# we can take the following approach 
IF hasattr (test_obj,'add'):
    fun = getattr(test_obj,'add')
    fun()
else:
    print('function is coming!!!')

# Above these what we are saying to call another file, reflected detection, 
# then the method for file themselves whether we can achieve reflection of it? 
# The answer is yes 
# define a method add it as a test subject 
DEF add (the X-, the y-):
     return the X-+ the y-
 Import SYS
TEST_1 = the sys.modules [ the __name__ ]
 Print (the hasattr (TEST_1, ' the Add ' ))
 # returns True, reflects itself represents 
# three other method is a way of

Second, on the __getattribute__

# __Getattribute __, __ getattr__ 
# On the surface, looks like both, so the specific relationship between them, what is it? 
# First test carried out a 
# class the Test: 
#      DEF __init __ (Self, Age): 
#          self.age = Age
#
#     def __getattr__(self, item):
#         print('getattr is coming!!!')
#     def __getattribute__(self, item):
#         print('getattribute is coming!!!')
#
# T1 = the Test (18) 
# First, we call this class some property 
# t1.age # interface output: getAttribute IS Coming !!! 
# Then we call a no property 
# t1.xxx # or output interface: iS Coming !!! getAttribute 
# previous __getattr__ how not to perform it?

# Let's redefine just what a class, and with some modifications, 
# to add a function method 
# while increasing raise AttributeError behind __getattribute__ ''

class Test:
    def __init__(self,age):
        self.age = age
    def test_1(self):
        return self.age
    # def __getattr__(self, item):
    #     print('getattr is coming!!!')
    # def __getattribute__(self, item):
    #     print('getattribute is coming!!!')
        # raise AttributeError('传递报错信息')

t1 = Test(18)
t1.age
Print (t1.test_1 ())
 # getAttribute IS Coming !!! 
# getattr IS Coming !!! 
# It should be noted that, getattribute is Python comes with function 
# When we perform a class of property, will first execution getattribute to find 
# If there is, then go directly to the corresponding property 
# after the will does not exist to summon his brother __getattr__ executed, the system default __getattr__ is not carried out, we have a defined content

Third, with regard to item series

class Foo:
    def __getitem__(self, item):
        print('getitem',item)
        return self.__dict__[item]

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

    def __delitem__(self, key):
        print('delitem')
        self.__dict__.pop(key)

f1=Foo()
print(f1.__dict__)
# f1.name='egon'  #---->setattr-------->f1.__dict__['name']='egon'
f1['name']='egon'#--->setitem--------->f1.__dict__['name']='egon'
f1['age']=18

print('===>',f1.__dict__)

# Of f1.name 
# print (f1 .__ dict__)
#
# print(f1.age)
del f1['name']
print(f1.__dict__)

Print (f1 [ ' Age ' ])
 The raise S
 # here should be understood by all objects. When calling the properties will trigger __attr__ 
# by dictionary [] is triggered when calling __item__

Fourth, on str, repr

# About str, in fact, built-in method __str__ 
# each class there will be a default __str__ method, we can get the results you want to modify it 
# class People: 
#      DEF __init __ (Self, name, Age) : 
#          self.name = name 
#          self.age = Age 
# p1 = People ( 'zhaolei', 18) 
# Print (p1) # <. __ main __ People Object aT 0x00000237F29FE908> 
# obviously we are in a period so do not want to see 
# also there are other cases 
# A = List ( 'HelloWorld') 
# Print (A) 
# [ 'H', 'E', 'L', 'L', 'O', 'W', 'O', 'R & lt' , 'l', 'd'] 
# In fact, we in essence print is triggered str () method 
# final trigger __str__

# So we modified for class method __str__ 
class the Test:
     DEF  __init__ (Self, name, Age):
            self.name = name
            self.age = age

    DEF  __str__ (Self):
         return  ' name:% s Age:% s ' % (self.name, self.age)

# At this point we re-instantiated and print 
T1 = the Test ( ' zhaolei ' , 18 )
 Print (T1)
 # Name: zhaolei Age: 18 
# at this time we can modify according to their needs, get print what you want status

# The following is a repr 
class Foo:
     DEF  __init__ (Self, name, Age):
        self.name=name
        self.age = Age
     # DEF __str __ (Self): 
    #      return 'is off STR' 
    DEF  __repr__ (Self):
         return  ' names are age% s% s ' % (the self.name, self.age)

F1 = Foo ( ' Egon ' ,. 19 )
 # the repr (F1) ----> F1 .__ the repr __ () 
Print (F1) # STR (F1) --- "F1 .__ STR __ () ------> .__ repr __ f1 () 
# that time if the system can not find __str__ will find __repr__

Fifth, on the format of the constructor

# x='{0}{0}{0}'.format('dog')
#
# print(x)

# class Date:
#     def __init__(self,year,mon,day):
#         self.year=year
#         self.mon=mon
#         self.day=day
# d1=Date(2016,12,26)
#
# x='{0.year}{0.mon}{0.day}'.format(d1)
# y='{0.year}:{0.mon}:{0.day}'.format(d1)
# z='{0.mon}-{0.day}-{0.year}'.format(d1)
# print(x)
# print(y)
# print(z)

# x='{0.year}{0.mon}{0.day}'.format(d1)
# y='{0.year}:{0.mon}:{0.day}'
# z='{0.mon}-{0.day}-{0.year}'

format_dic={
    'ymd':'{0.year}{0.mon}{0.day}',
    'm-d-y':'{0.mon}-{0.day}-{0.year}',
    'y:m:d':'{0.year}:{0.mon}:{0.day}'
}
class Date:
    def __init__(self,year,mon,day):
        self.year=year
        self.mon = my
        self.day=day
    def __format__(self, format_spec):
        print('我执行啦')
        print('--->',format_spec)
        if not format_spec or format_spec not in format_dic:
            format_spec='ymd'
        fm=format_dic[format_spec]
        return fm.format(self)
d1=Date(2016,12,26)
# format(d1) #d1.__format__()
# print(format(d1))
print(format(d1,'ymd'))
print(format(d1,'y:m:d'))
print(format(d1,'m-d-y'))
print(format(d1,'m-d:y'))
print('===========>',format(d1,'asdfasdfsadfasdfasdfasdfasdfasdfasdfasdfasdfasdfasd'))

Sixth, with regard to yesterday authorized the re-writing comments

import time
class Filehandle:
    def __init__(self,file_name , module = 'w+' , encoding = 'utf-8' ):
        self.file = open (file_name, Module, encoding = encoding)   # here encoding = encoding is very important, only then can we meet the requirements of the incoming string, think about the time before the use of open bar 
        self.name = file_name
        self.mode = module
        self.encoding = encoding

    DEF  __getattr__ (Self, Item):
         return getattr (self.file, Item)
     # where the main role is to redefine the way we do not need, we can use the normal mode of operation of the original file 
    # so that we can ensure that only we want to modify some modifications

    def write(self,line):
        print('------------>',line)
        t=time.strftime('%Y-%m-%d %X')
        self.file.write ( ' % S% S ' % (t, Line))
     # here we did not want to file an increased time in front of the content, so long has been amended accordingly 

f1 = FileHandle ( ' a.txt ' , ' W + ' )
f1.write ( ' Test line 1 \ n- ' )
time.sleep(3)
f1.write ( ' Test 2 OK \ n- ' )
time.sleep(3)
f1.write ( ' Test 3 rows \ n- ' )

# 2020-03-19 00:35:28 Test line 1 
# 2020-03-19 00:35:31 Test 2 rows 
# 2020-03-19 00:35:34 Test 3 rows

Today is the content, thank you for reading carefully

Guess you like

Origin www.cnblogs.com/xiaoyaotx/p/12521554.html