
class Animal():
def __init__(self, color):
self.color = color
@classmethod
def create_new_animal(cls):
print('创建一个新的动物种类')
>>> Animal.create_new_animal
<bound method Animal.create_new_animal of <class '__main__.Animal'>>
>>> Animal.create_new_animal() # 类调用类方法会将类本身当做第一个参数传给类方法
创建一个新的动物种类
class Animal():
def __init__(self, color):
self.color = color
@staticmethod
def create_new_animal(): # 静态方法没有自动传参的效果,就是普通的函数
print('创建一个新的动物种类')
>>> Animal.create_new_animal
<function Animal.create_new_animal at 0x000001DAE53CE670>
>>> Animal.create_new_animal()
创建一个新的动物种类
>>> Animal('white').create_new_animal()
创建一个新的动物种类
>>> class Test():
... test = 'test'
... def foo(self):
... print('test foo')
...
>>> dir(Test)
[..., 'foo', 'test']
>>> dir(Test())
[..., 'foo', 'test']
获取了对象的属性列表,需要借助Python解释器内置函数hasattr setattr getattr delattr通过字符串来操作对象的属性。
t = Test()
# hasattr(obj, '属性名'):判断对象是否有某个属性
>>> hasattr(t, 'test')
True
>>> hasattr(t, 'test1')
False
# setattr(obj, '属性名', '新的属性值'):修改对象的某个值,如果属性名不存在则为对象添加属性
>>> setattr(t, 'test', 'test1')
>>> setattr(t, 'test1', 'test1')
>>> t.test
'test1'
>>> t.test1
'test1'
# getattr(obj, '属性名') # 获取对象的属性值
>>> getattr(t, 'foo')
<bound method Test.foo of <__main__.Test object at 0x000001DAE4F9BF40>>
>>> getattr(t, 'test')
'test1'
>>> getattr(t, 'test1')
'test1'
# delattr(obj, '属性名') # 删除对象的属性
>>> delattr(t, 'test1')
>>> hasattr(t, 'test1')
False
基于反射可以通过字符串十分灵活的操作对象的属性,反射的原理其实就是基于对象.__dict__实现的。
# 1 先通过调用dir功能,查看某一个对象下可以 . 出哪些属性
print(dir(obj))
# 2 通过字符串反射到真正的属性,得到属性值
print(obj.__dict__[dir(obj)[-2]])
# 类中没有__str__方法
class Test:
def test(self):
print('test')
t = Test()
print(t) # <__main__.Test object at 0x000001F9EE618FD0>
# 类中有__str__
class Test:
def test(self):
print('test')
def __str__(self):
return 'Test对象'
t = Test()
print(t) # Test对象
__del__方法是在对象被删除时自动触发,由于python的垃圾回收机制会自动清理程序中没用的资源,因此如果一个对象只是占用应用程序的资源,没有必要定义__del__方法,但是如果设计到占用系统资源的话比如打开的文件对象,由于关系到操作系统的资源,python的垃圾回收机制派不上用场的时候,就需要为对象创建__del__方法,用于对象被删除后自动触发回收操作系统资源。
class Test:
def __init__(self):
self.x = open('a.txt',mode='w')
# self.x = 占用的是操作系统资源
def __del__(self):
print('run')
# 发起系统调用,告诉操作系统回收相关的系统资源
self.x.close()
obj = T()
del obj # obj.__del__()
转载请注明:XAMPP中文组官网 » python对象绑定方法 & 反射原理