Python基础-获取对象信息的常用函数

type()函数

基本数据类型

示例

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

运行结果

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()

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

print(dir(Person))

运行结果

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 0x0000000002C14BF8>
<bound method Man.toString of <Man.Man object at 0x0000000002C295C0>>

结语

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

法迪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值