标签:abs end sprint slow rac tin 存在 index 没有
在不知道对象信息的情况下,我们想要去获取对象信息,可以使用以下方法
>>> type(123) <class ‘int‘> >>> type("name") <class ‘str‘> >>> type(None) <class ‘NoneType‘> >>> type(abs) <class ‘builtin_function_or_method‘> >>> import Person >>> type(Person) <class ‘module‘>
>>> type(123)==type(456) True >>> type(123)==int True
#play.py
class Animals(object): def play(): pass class Dog(Animals): def play(): pass class Kity(Dog): def play(): pass a=Animals() d=Dog() k=Kity()
>>> import play >>> isinstance(k,Kity) True >>> isinstance(k,Dog) True >>> isinstance(k,Animals) True >>> isinstance(k,object) True >>> isinstance(d,Kity) False
>>> isinstance(123,(str,int))
True
获得一个对象的所有属性和方法
>>> dir("Alice") [‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘capitalize‘, ‘casefold‘, ‘center‘, ‘count‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘, ‘format_map‘, ‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdecimal‘, ‘isdigit‘, ‘isidentifier‘, ‘islower‘, ‘isnumeric‘, ‘isprintable‘, ‘isspace‘, ‘istitle‘, ‘isupper‘, ‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘, ‘maketrans‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]
>>> class Cal(object): x=2 def cal(): self.y=1 return x+y >>> ca=Cal() >>> hasattr(ca,"x") True >>> setattr(ca,"z",3) >>> getattr(ca,"z") 3 >>> getattr(ca,"p")
如果试图获取某个不存在的属性会报错
可以传入一个default参数,如果想获取的属性不存在,就返回默认值
>>> getattr(ca,"p") Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> getattr(ca,"p") AttributeError: ‘Cal‘ object has no attribute ‘p‘ >>> getattr(ca,"p",404) 404
通过实例变量给实例绑定属性
标签:abs end sprint slow rac tin 存在 index 没有
原文地址:https://www.cnblogs.com/finsomway/p/10037647.html