什么是BIF
BIF即Bulit Internal Function,意为内置方法。
判断一个对象有无某个属性
hasattr()
全名为:has attribute ? 有某个属性吗?
例:
class Person(object):
def __init__(self):
self.home = 'earth'
def sayHi(self):
print('Hi,baby!')
chinese = Person()
print(hasattr(chinese,'home'))
print(hasattr(chinese,'sayHi'))
print(hasattr(chinese,'name'))
输出:
➜ test git:(master) ✗ python3 test.py
True
True
False
home是chinese实例的一个变量属性,在__init__初始化时定义,sayHi是chinese实例的一个方法属性。
获取一个对象的属性
getattr()
全名为:get attribute,获取属性。
例:
class Person(object):
def __init__(self):
self.home = 'earth'
def sayHi(self):
print('Hi,baby!')
chinese = Person()
my_home = getattr(chinese,'home') # 获取对象的变量属性
my_say = getattr(chinese,'sayHi') # 获取对象的方法属性
my_age = getattr(chinese,'age','您所查找的属性不存在') # 设置默认返回值
print(my_home,my_say,my_age,sep='\n')
my_name = getattr(chinese,'name') # 获取不存在的属性,会报AttributeError的错误
print(my_name)
输出:
➜ test git:(master) ✗ python3 test.py
earth
<bound method Person.sayHi of <__main__.Person object at 0x7f123fefdf28>>
您所查找的属性不存在
Traceback (most recent call last):
File "test.py", line 59, in <module>
my_name = getattr(chinese,'name')
AttributeError: 'Person' object has no attribute 'name'
获取的方法属性还可以拿来执行:
# 执行
my_say()
# 输出
Hi,baby!
设置对象的属性
setattr()
全名为:set attribute,设置属性。
例:
class Person(object):
def __init__(self):
self.home = 'earth'
def sayHi(self):
print('Hi,baby!')
chinese = Person()
my_home = setattr(chinese,'home','china')
print(chinese.home)
输出:
➜ test git:(master) ✗ python3 test.py
china
其余详细内容请移步:Python面向对象的反射