Python基础知识(17):面向对象编程(Ⅱ)
获取对象信息
在不知道对象信息的情况下,我们想要去获取对象信息,可以使用以下方法
1、type
(1)判断对象类型
>>> 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‘>
(2)比较两个对象是否是同一个类型
>>> type(123)==type(456) True >>> type(123)==int True
2、isinstance
(1)判断一个对象是否是该类型本身或位于该类型的父类继承链
#play.pyclass 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
(2)判断一个变量是否是某些类型中的其中一种
>>> isinstance(123,(str,int)) True
3、dir
获得一个对象的所有属性和方法
>>> 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‘]
测试对象属性
hasattr:有没有该属性
setattr:设置该属性
getattr:获取该属性
>>> 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
实例属性和类属性
1、实例属性属于各个实例所有,互不干扰
通过实例变量给实例绑定属性
2、类属性属于类所有,所有实例都可以使用
3、当实例属性和类属性名字相同时,类属性将会被屏蔽
原文地址:https://www.cnblogs.com/finsomway/p/10037647.html
时间: 2024-10-18 14:55:34