首页 > Python3教程 > Python3类与面向对象

Python3 查看对象详细信息

Python3 使用type、isinstance和dir函数来查看对象详细信息(对象类型,属性,方法等)

使用type()函数

type函数用于判断对象类型,也能用于基本数据类型的判断,还能用于函数的判断。

class Lesson(object):
student = "you" # 公有的类属性
__nu = 2 # 私有的类属性

# 对象的构造方法(初始化)方法
def __init__(self, name, score):
self.name = name # 公有的类实例属性
self.score = score # 公有的类实例属性

def print_score(this):
print('%s: %s' % (this.name, this.score))

# 实例化对象
lesson1 = Lesson('python', 90)

print(type(lesson1)) # 判断对象类型
print(type(lesson1.print_score)) # 判断函数
print(type(1)) # 判断基本数据类型

Python3 查看对象详细信息

使用isinstance()函数

对于类的继承关系来说,使用type()很不方便。我们要判断类的类型,要使用isinstance()函数

isinstance()判断的是一个对象是否是该类型本身,或者是否是该类型的父类。

isinstance()也能用于判断基本数据类型,还能判断一个变量是否是某些类型中的一种。

class Lesson(object):
student = "you" # 公有的类属性
__nu = 2 # 私有的类属性

# 对象的构造方法(初始化)方法
def __init__(self, name, score):
self.name = name # 公有的类实例属性
self.score = score # 公有的类实例属性

def print_score(this):
print('%s: %s' % (this.name, this.score))

# 实例化对象
lesson1 = Lesson('python', 90)

a = isinstance(lesson1, Lesson)
print(a) # 输出True

a = isinstance(1, int)
print(a) # 输出True

a = isinstance([1, 2, 3], (list, tuple))
print(a) # 输出True

 

使用dir()函数

要获得一个对象的所有属性和方法,就使用dir()函数,它返回一个包含字符串的list

getattr()函数获取属性、setattr()函数设置属性以及hasattr()函数判断是否有某个属性

class Lesson(object):
student = "you" # 公有的类属性
__nu = 2 # 私有的类属性

# 对象的构造方法(初始化)方法
def __init__(self, name, score):
self.name = name # 公有的类实例属性
self.score = score # 公有的类实例属性

def print_score(this):
print('%s: %s' % (this.name, this.score))

# 实例化对象
lesson1 = Lesson('python', 90)

a = dir(lesson1)
# 输出 ['_Lesson__nu', '__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__', 'name', 'print_score', 'score', 'student']
print(a)

setattr(lesson1, 'student', 19) # 设置属性'student'
a = hasattr(lesson1, 'student') # 有属性'student'
print(a)
a = getattr(lesson1, 'student') # 获取属性'student'
print(a)
a = getattr(lesson1, 'y', 'you') # 获取属性'y',如果不存在,返回默认值you
print(a)

 

关闭
感谢您的支持,我会继续努力!
扫码打赏,建议金额1-10元


提醒:打赏金额将直接进入对方账号,无法退款,请您谨慎操作。