天天看点

Python基础-获取对象信息的常用函数type()函数isinstance()dir()getattr()、setattr()以及hasattr()结语

type()函数

基本数据类型

示例

print(type() == type("1"))
print(type() == type())
           

运行结果

False
True
           

对象

两个对象分别为

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 继承

from Person import *

# Man 继承了 Person 的所有方法
class Man(Person):

    # 子类只有的方法
    def manPrint(self):
        print("I' m  a man")

    # 多态,重新父类的方法
    def toString(self):
        print("重新父类方法,体现 多态 %s : %s" % (self.name, self.age))
=================================================       
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"Person绫?

class Person(object):

    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def setName(self, name):
        self.__name  = name

    def getName(self):
        return self.__name

    def setAge(self, age):
        self.__age = age

    def getAge(self):
        return self.__age

    def toString(self):
        print("%s:%s"%(self.__name, self.__age))
           

同样使用type

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 继承
from Man import *
from Person import *

# 运行结果 True
print(type(Man) == type(Person))
           

isinstance()

是否有class的继承关系

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 继承
from Man import *
from Person import *

mPerson = Person("女娲娘娘","888")
mMan = Man("韦小宝", "18")

result = isinstance(mPerson, Man)
# 运行结果:True
print(result)

result = isinstance(mMan, Person)
# 运行结果:False
print(result)
           

dir()

获得一个对象的所有属性和方法

示例

运行结果

D:\PythonProject\sustudy>python main.py
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
 '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '
__str__', '__subclasshook__', '__weakref__', 'getAge', 'getName', 'setAge', 'setName', 'toString']
           

getattr()、setattr()以及hasattr()

示例

if(hasattr(Man, 'toString')):
    result = getattr(Man, 'toString')
    print(result)

if(hasattr(mMan, 'toString')):
    result = getattr(mMan, 'toString')
    print(result)
           

运行结果

D:\PythonProject\sustudy>python main.py
<function Man.toString at >
<bound method Man.toString of <Man.Man object at >>
           

结语

本章很空洞,知道有这些常见函数就行了,尴尬