Python_day_08_魔术方法

1._format魔术方法

_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')

# __format__    format(d)


# format(d, 'ymd')  === "2018-01-09"

2._切片魔术方法

from collections import Iterable

class Student(object):
    def __init__(self, name):
        self.name = name
        self.score = [100, 90, 89]

    # 判断一个类的对象是否可以迭代, 看类是否有__iter__方法
    # 自己定义迭代的规则;
    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):
        # 访问某个属性时, s['key']
        pass

    def __setitem__(self, key, value):
        # 给某个属性赋值使用; s['key']=value
        print key, value

    def __delitem__(self, key):
        pass

s1 = Student('fentiao')
s2 = Student('fendai')
# print isinstance(s1, Iterable)
# for i in s1:
#     print i
#
# print s1 ==  s2
# print s1 >  s2

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]

4._字符串显示之format

# format通过位置符号
print "{0:.2f}:{1:d}:{0}".format(1,2)

# format使用名称
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
        # 0: 借出, 1:未借出
        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):
        # 访问某个属性时, s['key']
        return self.__dict__[item]

    def __setitem__(self, key, value):
        # 给某个属性赋值使用; s['key']=value
        # print 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']
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页