day5获取对象信息

"""
isinstance(),可以判断一个对象是否是某个类型
type(),可以获得变量的类型
"""
print(isinstance('123', str)) # True
print(type('123')) # <class 'str'>


# 打印实例化对象的类型
class Person:
def __init__(self, name, gender):
self.name = name
self.gender = gender

class Student(Person):
def __init__(self, name, gender, score):
super().__init__(name, gender)
self.score = score

p = Person('Alice', 'Female')
s = Student('Bob', 'Male', 100)

print(type(p))
print(type(s))

"""
打印结果:
<class '__main__.Person'>
<class '__main__.Student'>
"""


"""
通过dir()方法,可以获取变量的所有属性:返回结果是列表
在dir列出的属性中,有很多是以下划线开头和结尾的,这些都是特殊的方法,称为内建方法
"""
n = 1
print(dir(n))
"""
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__',
'__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__',
'__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__',
'__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__',
'__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__',
'__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__',
'__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__',
'__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator',
'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
"""

print(dir(p))
"""
['__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__', 'gender', 'name']
"""



"""
dir()返回的属性是字符串列表,如果已知一个属性名称,要获取或者设置对象的属性,就需要用 getattr() 和 setattr( )函数了。
"""
print(getattr(p, 'name')) # Alice,类似 p.name
setattr(p, 'name', 'zoey') # 设置新的name属性,类似于 p.name = 'zoey'
print(p.name) # zoey

# print(getattr(p, 'age')) # AttributeError: 'Person' object has no attribute 'age'
print(getattr(p, 'age', 20)) # 20, 获取age属性,如果属性不存在,就返回默认值20


# 练习:希望除了name和gender外,可以提供任意额外的关键字参数,并绑定到实例,请修改 Person 的__init__()定义,完成该功能
class Person:
def __init__(self, name, gender, **kwargs):
self.name = name
self.gender = gender
for k, v in kwargs.items():
setattr(self, k, v)


p = Person('Bob', 'Male', age=18, course='Python')
print(p.name)
print(p.age)
print(p.course)

"""
打印结果:
Bob
18
Python
"""
posted @ 2023-03-06 23:54  雪儿来  阅读(8)  评论(0编辑  收藏  举报