首页 / PYTHON / python的魔术方法
python的魔术方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python的魔术方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2095字,纯文字阅读大概需要3分钟。
内容图文
![python的魔术方法](/upload/InfoBanner/zyjiaocheng/846/dc8a30a40c8d4f529e460f3bda1ca1b1.jpg)
什么叫魔术方法:
在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主要的作用就是将方法的调用伪装为一个属性的查找方式
内容总结
以上是互联网集市为您收集整理的python的魔术方法全部内容,希望文章能够帮你解决python的魔术方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。