面向对象之自省与反射
语言范畴划分编译型和解释型语言关于编译性与解释型语言的区别,在 强类型和弱类型语言
动态型和静态性语言
自省与反射Python中的自省与反射
from collections import UserList class MyList(UserList): """测试专用...""" MyList_author = "Yunya" pass # ==== 常用方法 ==== print(dir(MyList)) print(hasattr(MyList,append")) <--- 注意,必须是字符串 True list_method = getattr(MyList,1)">MyList_author",1)">没有该值") print(list_method) Yunya setattr(MyList,云崖) print(MyList.MyList_author) 云崖 delattr(MyList,1)"> False ==== 其他方法 ==== print(issubclass(MyList,UserList)) True print(isinstance(1,int)) print(id(MyList)) 2150657427760 print(callable(MyList)) True help(MyList) ==== 执行结果 ==== ['MyList_author','_UserList__cast','__abstractmethods__','__add__','__class__','__contains__','__copy__','__delattr__','__delitem__','__dict__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__gt__','__hash__','__iadd__','__imul__','__init__','__init_subclass__','__iter__','__le__','__len__','__lt__','__module__','__mul__','__ne__','__new__','__radd__','__reduce__','__reduce_ex__','__repr__','__reversed__','__rmul__','__setattr__','__setitem__','__sizeof__','__slots__','__str__','__subclasshook__','__weakref__','_abc_impl','append','clear','copy','count','extend','index','insert','pop','remove','reverse','sort'] True Yunya 云崖 False True True 2150657427760 True Help on class MyList in module __main__: class MyList(collections.UserList) | MyList(initlist=None) | | 测试专用... | | Method resolution order: | MyList | collections.UserList | collections.abc.MutableSequence | collections.abc.Sequence | collections.abc.Reversible | collections.abc.Collection | collections.abc.Sized | collections.abc.Iterable | collections.abc.Container | builtins.object | | Data and other attributes defined here: | | __abstractmethods__ = frozenset() | | ---------------------------------------------------------------------- | Methods inherited from collections.UserList: | | __add__(self,other) | | __contains__(self,item) | | __copy__(self) | | __delitem__(self,i) | | __eq__(self,other) | Return self==value. | | __ge__(self,other) | Return self>=value. | | __getitem__(self,i) | | __gt__(self,other) | Return self>value. | | __iadd__(self,other) | | __imul__(self,n) | | __init__(self,initlist=None) | Initialize self. See help(type(self)) for accurate signature. | | __le__(self,other) | Return self<=value. | | __len__(self) | | __lt__(self,other) | Return self<value. | | __mul__(self,n) | | __radd__(self,other) | | __repr__(self) | Return repr(self). | | __rmul__ = __mul__(self,n) | | __setitem__(self,i,item) | | append(self,item) | S.append(value) -- append value to the end of the sequence | | clear(self) | S.clear() -> None -- remove all items from S | | copy(self) | | count(self,item) | S.count(value) -> integer -- return number of occurrences of value | | extend(self,other) | S.extend(iterable) -- extend sequence by appending elements from the iterable | | index(self,item,*args) | S.index(value,[start,[stop]]) -> integer -- return first index of value. | Raises ValueError if the value is not present. | | Supporting start and stop arguments is optional,but | recommended. | | insert(self,item) | S.insert(index,value) -- insert value before index | | pop(self,i=-1) | S.pop([index]) -> item -- remove and return item at index (default last). | Raise IndexError if list is empty or index is out of range. | | remove(self,item) | S.remove(value) -- remove first occurrence of value. | Raise ValueError if the value is not present. | | reverse(self) | S.reverse() -- reverse *IN PLACE* | | sort(self,/,*args,**kwds) | | ---------------------------------------------------------------------- | Data descriptors inherited from collections.UserList: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from collections.UserList: | | __hash__ = None | | ---------------------------------------------------------------------- | Methods inherited from collections.abc.Sequence: | | __iter__(self) | | __reversed__(self) | | ---------------------------------------------------------------------- | Class methods inherited from collections.abc.Reversible: | | __subclasshook__(C) from abc.ABCMeta | Abstract classes can override this to customize issubclass(). | | This is invoked early on by abc.ABCMeta.__subclasscheck__(). | It should return True,False or NotImplemented. If it returns | NotImplemented,the normal algorithm is used. Otherwise,it | overrides the normal algorithm (and the outcome is cached). """ 应用场景==== 这样做的好处是即使用户输入有误,也不会抛出异常 ==== sys DownloadAndUpload(object): def __init__(self): self.val = sys.argv[1] self.select() def download(self): print(正在下载...) upload(self): 正在上传... select(self): if hasattr(self,self.val): getattr(self,self.val)() else: 没有该方法) DownloadAndUpload()? 扩展与后言:反射内部实现机制其实我想了好一会要不要写这个,内部实现机制。这一些内容应该放在双下方法学完之后才应该讲反射实现的内部机制。所以这里提一嘴:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |