Python There are some magical ways to do it , They are always surrounded by double underscores , They are object-oriented Of Python Everything . They are special ways to add magic to your classes , If your object implements ( heavy load ) A magic method , Then this method will be automatically used in special cases Python The call .
Definition object is format() The behavior of a function call , It is often used for formatted output of strings .
self Represents an object ;format_spec Represents a format controller ( Customizable ), It will receive ’:‘ String after ( Such as ’{0: string}’.format(object) , Will string ’string’ Pass to format_spec)
Must be a string , Otherwise, throw an exception .
date_dic = {
'ymd': '{0.year}:{0.month}:{0.day}',
'dmy': '{0.day}/{0.month}/{0.year}',
'mdy': '{0.month}-{0.day}-{0.year}',
}
class MyText:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __format__(self, format_spec):
if not format_spec or format_spec not in date_dic:
format_spec = 'ymd'
fmt = date_dic[format_spec]
return fmt.format(self)
d1 = MyText(2019, 9, 17)
# 2019: 9:17
print('{0:ymd}'.format(d1))
Execution results :
2019:9:17
Can be overloaded in classes __format__ function , In this way, you can directly pass through format Function to call the object , Output the desired results .
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 'x: %s, y: %s' % (self.x, self.y)
def __format__(self, code):
return 'x: {x}, y: {y}'.format(x=self.x, y=self.y)
p = Point(3, 5)
print(f'this point is {p}')
Execution results :
this point is x: 3, y: 5
By overloading __format__ Method , The original fixed format logic is made configurable . This greatly increases the flexibility in the use process , This flexibility can greatly simplify and simplify the code in some problem scenarios .
# 01_mnist_demo.py # Usi