面向对象3
isinstance(对象, 类):检查对象是否类
class Foo:
pass
foo = Foo()
print(isinstance(foo, Foo))
True
issubclass:检查继承关系
class Foo:
pass
class Bar(Foo):
pass
class Car(Bar):
pass
# foo = Foo()
# print(isinstance(foo, Foo))
print(issubclass(Bar, Foo))
print(issubclass(Car, Foo))
True
True
反射
所谓反射,是指程序可以访问、检测和修改它本身状态或者行为的一种能力(自省)
在Python中,面向对象中的反射是指通过字符串的形式操作对象的相关属性。
四个可以实现自省的函数
attribute
-
hasattr
-
hasatter(*args, **kwargs)
-
"""Return whether the object has an attribute with the given name. This is done by calling getattr(obj, name) and catching AttributeError."""
-
-
getattr
-
getattr(object, name, default=None)
-
"""getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.When a default argument is given, it is returned when the attribute doesn'texist; without it, an exception is raised in that case."""
-
-
setattr
-
setattr(x, y, v)
-
"""Sets the named attribute on the given object to the specified value.setattr(x, 'y', v) is equivalent to ``x.y = v''"""
-
-
delattr
-
delattr(x, y)
-
"""Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y''"""
-
class Foo:
f = '类的静态变量'
def __init__(self,name, age):
self.name = name
self.age = age
def say(self):
print('hello, %s' % self.name)
obj = Foo('Tom', 12)
#检测是否含有某个属性
print(hasattr(obj, 'name'))
print(hasattr(obj, 'age'))
print(hasattr(obj, 'say'))
#获取属性
gt = getattr(obj, 'say') #获取了函数
gt() #调用函数
gef = getattr(obj, 'name') #获取了属性
print(gef) #显示属性
#设置属性
setattr(obj, 'good man', True)
setattr(obj, 'show_name', lambda self: self.name + 'good man')
print(obj.__dict__)
print(obj.show_name(obj))
#删除属性
delattr(obj, 'show_name')
print(obj.__dict__)
True
True
True
hello, Tom
Tom
{'name': 'Tom', 'age': 12, 'good man': True, 'show_name': <function <lambda> at 0x000001A4CF06AA60>}
Tomgood man
{'name': 'Tom', 'age': 12, 'good man': True}
item系列
class Foo:
def __init__(self, name):
self.name = name
def __getitem__(self, item):
print(self.__dict__[item])
def __setitem__(self, key, value):
self.__dict__[key] = value
def __delitem__(self, key):
print('del obj[key]时')
self.__dict__.pop(key)
def __delattr__(self, item):
print('def obj.key时')
self.__dict__.pop(item)
obj1 = Foo('Tom')
obj1['age'] = 18
print(obj1.__dict__)
del obj1['age']
del obj1.name
print(obj1.__dict__)
{'name': 'Tom', 'age': 18}
del obj[key]时
def obj.key时
{}
__del__
析构钢发,当对象在内存中被释放,就会自动触发执行。
一般不需要定义
因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。
class Foo:
def __del__(self):
print('执行DEL函数了')
obj = Foo()
del obj
执行DEL函数了
__str__
- 如果直接print打印对象。会看到创建对象的内存地址。
- 当我们使用print(xxx), 输出对象,如果对象中定义了
__str__
方法,就会打印该方法return的信息描述
class Cat:
def __init__(self, new_name, new_age):
self.name = new_name
self.age = new_age
def __str__(self):
return '名字是 %s, 年龄是 %s' %(self.name, self.age)
cat = Cat('Tom', 18)
print(cat)
名字是 Tom, 年龄是 18