10.python3實用編程技巧進階(五)

5.1.如何派生內置不可變類型並修其改實例化行爲

修改實例化行爲ui

# 5.1.如何派生內置不可變類型並修其改實例化行爲

#繼承內置tuple, 並實現__new__,在其中修改實例化行爲
class IntTuple(tuple):
    def __new__(cls, iterable):
        #過濾掉元祖中不是int類型且小於0的元素
        f_it = (e for e in iterable if isinstance(e, int) and e > 0)
        return super().__new__(cls, f_it)

int_t = IntTuple([1, 8, -2, -3, 'abc', [4,5], 10])

print(int_t)    #(1, 8, 10)

5.2.如何爲建立大量實例節省內存

定義類的__slots__屬性,聲明實例有哪些屬性(關閉動態綁定)spa

#5.2.如何爲建立大量實例節省內存

class Player1:
    def __init__(self,uid, name, level):
        self.uid = uid
        self.name = name
        self.level = level


class Player2:
    #定義類的__slots__屬性,聲明實例有哪些屬性(關閉動態綁定)
    __slots__ = ['uid', 'name', 'level']
    def __init__(self,uid, name, level):
        self.uid = uid
        self.name = name
        self.level = level

p1 = Player1(1,'derek',20)
p2 = Player2(2,'jack',50)
print(p1.name)
print(p2.name)
#能夠爲實例動態添加屬性,可是這樣會消耗內存
p1.age = 18
print(p1.__dict__['age'])    #18

#用__slot__聲明瞭實例有哪些屬性後,則不能動態爲實例添加屬性
#p2.age = 22    #AttributeError: 'Player2' object has no attribute 'age'

 5.3.如何建立可管理的對象屬性

通常寫法code

#5.3.如何建立可管理的對象屬性

class Student():
    def __init__(self,score):
        self.score = score

    def get_score(self):
        return self.score

    def set_score(self, score):
        if not isinstance(score, int):
            raise TypeError("wrong type")
        self.score = score

s = Student(70)
print(s.get_score())

s.set_score(80)
print(s.score)

用property裝飾器對象

#5.3.如何建立可管理的對象屬性

class Student():
    def __init__(self,score):
        self.score = score

    @property
    def value(self):
        return self.score

    @value.setter
    def value(self, score):
        if not isinstance(score, int):
            raise TypeError("wrong type")
        self.score = score

s = Student(70)
print(s.value)

s.value = 80
print(s.value)
相關文章
相關標籤/搜索