classPerson(object):
def__init__(self, name, age):
self.name = name
self.age = age
deftell(self):
print(f'{self.name} is {self.age} years old')
@classmethoddeftalk(cls):
print(cls.__name__)
@staticmethoddefswim():
print(f'I am a swimming')
# 实例化得到一个对象
people = Person(name='chosen', age=18)
(1)getattr(obj,key)
# (1)数据属性# 在对象中映射数据属性的时候,如果对象中存在当前属性值则直接将属性值拿出来
result = getattr(people,'name')
print(result) # chosen
result = getattr(people,'age')
print(result) # 18# (2)函数属性# 在对象中映射函数属性的时候,如果对象中存在当前属性名对应的数据属性# 则直接获取当前函数属性的内存地址,可以直接调用当前函数# result = getattr(people,'tell')# print(result) # <bound method Person.tell of <__main__.Person object at 0x000001D755913E50>># result()# (3)不存在# 在对象中映射属性的时候,如果对象中不存在当前属性名对应的属性,会直接报错
result = getattr(people,'gender')
print(result) # AttributeError: 'Person' object has no attribute 'gender'
(2)hasattr(obj,key)
# (1)数据属性# 在对象中映射数据属性的时候,如果对象中存在当前属性值则返回True
result = hasattr(people,'name')
print(result) # True
result = hasattr(people,'age')
print(result) # True# (2)函数属性# 在对象中映射函数属性的时候,如果对象中存在当前属性名对应的数据属性,则返回True
result = hasattr(people,'tell')
print(result) # True# (3)不存在# 在对象中映射属性的时候,如果对象中不存在当前属性名对应的属性,则返回False
result = hasattr(people,'gender')
print(result) # False
(3)setattr(obj,key,value)
# (1)数据属性# 向对象中设置属性名和属性值,如果对象中存在当前属性则直接替换,否则新增
result = setattr(people, 'name', 'hope')
print(result) # None
result = setattr(people, 'gender', 'male')
print(result) # Noneprint(people.name) # hopeprint(people.gender) # male# (2)函数属性defread():
print(f"这是外部的 read ")
# 在对象中映射函数属性的时候,如果对象中存在当前属性名对应的数据属性,则返回True
result = setattr(people, 'read', read)
print(result) # Noneprint(hasattr(people, 'read')) # Trueprint(getattr(people, 'read')) # <function read at 0x00000139777D7B80>getattr(people, 'read')() # 这是外部的 readprint(people.tell) # <bound method Person.tell of <__main__.Person object at 0x000001CDFDE8C640>>print(people.talk) # <bound method Person.talk of <class '__main__.Person'>>print(people.swim) # <function Person.swim at 0x000001997CB5C790>
(4)delattr(obj,key)
# (1)数据属性# 在对象中删除数据属性的时候,如果对象中存在当前属性值则直接删除print(hasattr(people,'name')) # True
result = delattr(people,'name')
print(result) # Noneprint(hasattr(people,'name')) # False# (2)函数属性# 在对象中删除函数属性的时候,要根据参数是对象还是类来做区分print(hasattr(Person, 'tell')) # True# 如果参数是当前对象,则无法删除函数属性
result = delattr(people, 'tell')
result = delattr(people, 'talk')
result = delattr(people, 'swim')
# 如果参数是当前类,则可以删除函数属性
result = delattr(Person, 'tell') #
result = delattr(Person, 'talk')
result = delattr(Person, 'swim')
print(result) # Noneprint(hasattr(Person, 'swim'))
# (3)不存在# 在对象中删除属性的时候,如果对象中不存在当前属性名对应的属性,则直接报错
result = delattr(people,'gender')
print(result) #AttributeError: gender
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!