程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python magic method (7):__ format __ (self, format_spec) method

編輯:Python

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 .

function

Definition object is format() The behavior of a function call , It is often used for formatted output of strings .

Parameters

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)

Return value

Must be a string , Otherwise, throw an exception .

Example

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved