当前位置 : 主页 > 编程语言 > python >

python对象的自省机制

来源:互联网 收集:自由互联 发布时间:2022-06-15
#自省是通过一定的机制查询到对象的内部结构 from chapter04.class_method import Date class Person: """ 人 """ name = "user" class Student(Person): def __init__(self, scool_name): self.scool_name = scool_name if __name__ ==
#自省是通过一定的机制查询到对象的内部结构
from chapter04.class_method import Date
class Person:
"""

"""
name = "user"

class Student(Person):
def __init__(self, scool_name):
self.scool_name = scool_name

if __name__ == "__main__":
user = Student("北京大学")

#通过__dict__查询属性
# print(user.__dict__)
# user.__dict__["school_addr"] = "北京市"
# print(user.school_addr)
# print(Person.__dict__)
# print(user.name)
a = [1,2]
print(dir(a))

  ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']


#自省是通过一定的机制查询到对象的内部结构
from class_method import Date
class Person:
"""

"""
name = "user"

class Student(Person):
def __init__(self, scool_name):
self.scool_name = scool_name

if __name__ == "__main__":
user = Student("北京大学")

#通过__dict__查询属性
print(user.__dict__)
user.__dict__["school_addr"] = "北京市"
print(user.school_addr)
print(Person.__dict__)
print(user.name)
# a = [1,2]
# print(dir(a))


{'scool_name': 北京大学'}

北京市
{'name': 'user', '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__module__': '__main__', '__doc__': '\n 人\n ', '__dict__': <attribute '__dict__' of 'Person' objects>}
user



网友评论