_formats = {
'ymd': '{d.year}-{d.month}-{d.day}',
'mdy': '{d.month}/{d.day}-{d.year}',
'dmy': '{d.day}/{d.month}/{d.year}',
}
class Date(object):
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __format__(self, code):
if code == '':
code = 'ymd'
fmt = _formats[code]
return fmt.format(d=self)
d = Date(2018, 1, 9)
print format(d, 'ymd')
print format(d, 'mdy')
print format(d, 'dmy')
2._切片魔术方法
from collections import Iterable
class Student(object):
def __init__(self, name):
self.name = name
self.score = [100, 90, 89]
def __iter__(self):
return iter(self.score)
def __eq__(self, other):
avg_score1 = sum(self.score)/len(self.score)
avg_score2 = sum(other.score)/len(other.score)
return avg_score1 == avg_score2
def __le__(self, other):
pass
def __ge__(self, other):
pass
def __getitem__(self, item):
pass
def __setitem__(self, key, value):
print key, value
def __delitem__(self, key):
pass
s1 = Student('fentiao')
s2 = Student('fendai')
print s1[1:2]
3._切片魔术方法
from collections import Iterable
class Student(object):
def __init__(self, name):
self.name = name
self.score = [100, 90, 89, 100, 89]
def __getslice__(self,i, j):
return self.score[i:j]
def __setslice__(self, i, j, item):
self.score[i:j] = item
def __delslice__(self, i, j):
del self.score[i:j]
s1 = Student('fentiao')
print s1[1:4]
s1[1:4]=[0, 0, 0]
print s1[1:5]
s1[1:4]= [100, 90, 80]
del s1[0:3]
print s1[0:5]
print "{0:.2f}:{1:d}:{0}".format(1,2)
print "max:{max}\n\nmin:{min}".format(min=10, max=100)
class Book(object):
def __init__(self, name, author, state, bookIndex):
self.name = name
self.author = author
self.state = state
self.bookIndex = bookIndex
def __str__(self):
return "Book({d.name}, {d.author}, {d.state})".format(d=self)
b = Book('a','a', 1, 'IN9008')
print b
5. 格式化元组的具体项
point = (1,3)
print 'X:{0[0]};Y:{0[1]}'.format(point)
goods = [
("001", 'computer', 100, 4000),
("002", 'apple', 1000, 4),
("003", 'xiaomi', 100, 3000),
]
formatter = "编号:{0[0]}\t 名称:{0[1]}\t数量:{0[2]}\t价格:{0[3]}".format
for i in map(formatter,goods):
print i
6._getitem魔术方法
from collections import Iterable
class Student(object):
def __init__(self, name):
self.name = name
self.score = [100, 90, 89]
def __getitem__(self, item):
return self.__dict__[item]
def __setitem__(self, key, value):
if isinstance(key, str):
try:
node = self.__dict__[key]
except:
self.__dict__[key] = value
self.__dict__[key] = value
def __delitem__(self, key):
pass
s = Student('fentiao')
print s.__dict__
s['key'] = 'value'
s['hello'] = 'a1'
s['key1'] = 'value2'
print s['key1']