1. 程式人生 > >python的魔術方法

python的魔術方法

什麼叫魔術方法:

在python中定義以雙下劃線開頭,有一些python自定義的函式,並且以雙下劃線為結尾的函式叫做魔法函式

class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list

    def __getitem__(self, item):
        return self.employee[item]

    def __len__(self):
        return len(self.employee)


company 
= Company(["tom", "bob", "jane"]) company1 = company[:2] print(len(company)) for em in company1: print(em)

當中間定義了__getitem__方法,就將Company變成了一個可迭代物件,呼叫for迴圈時,python會一個一個嘗試,直到報錯。所以列印print(len(company1))不會報錯

__subclasshook__:

這個魔術方法有什麼用呢?

使用__subclasshook__後只要具體類定義了與抽象類相同的方法就認為是他的子類

 

import abc
 
class A(object):
  __metaclass__ = abc.ABCMeta
 
  @abc.abstractmethod
  def say(self):
    return 'say yeah'
 
  @classmethod
  def __subclasshook__(cls, C):
    if cls is A:
      if any("say" in B.__dict__ for B in C.__mro__):
        return True
    return NotTmplementd
 
class
B(object): def say(self): return 'hello' print issubclass(B, A) # True print isinstance(B(), A) # True print B.__dict__ # {'say': <function say at 0x7f...>, ...} print A.__subclasshook__(B) # True

 3,__getattr__ 和__getattribute__區別

# __getattr__, __getattribute__
# __getattr__ 就是在查詢不到屬性的時候呼叫
from datetime import date


class User:
    def __init__(self, info={}):
        self.in fo = info

    def __getattr__(self, item):
        return self.info[item]

    # def __getattribute__(self, item):
    #     return "bobby"  這個是任何時候都會 進入的,不管是否報錯


if __name__ == "__main__":
    user = User(info={"company_name": "imooc", "name": "bobby"})
    print(user.test)

4,property_test

from datetime import date, datetime


class User:
    def __init__(self, name, birthday):
        self.name = name
        self.birthday = birthday
        self._age = 0  # 宣告不想被修改的屬性

    # def get_age(self):
    #     return datetime.now().year - self.birthday.year

    @property
    def age(self):
        return datetime.now().year - self.birthday.year

    @age.setter
    def age(self, value):
        self._age = value


if __name__ == "__main__":
    user = User("bobby", date(year=1987, month=1, day=1))
    user.age = 30
    print(user._age)
    print(user.age)

其實property主要的作用就是將方法的呼叫偽裝為一個屬性的查詢方式