- >>>class A(object):
- ... bar = 1
- ...
- >>> a = A()
- >>> getattr(a, 'bar') # 获取属性 bar 值
- 1
- >>> getattr(a, 'bar2') # 属性 bar2 不存在,触发异常
- Traceback (most recent call last):
- File "
" , line 1, in - AttributeError: 'A' object has no attribute 'bar2'
- >>> getattr(a, 'bar2', 3) # 属性 bar2 不存在,但设置了默认值
- 3
- >>>
-
- #(2)hasattr()怎么使用
- class A:
- def func1(self):
- return "csdewf"
- a = A()
- print(hasattr(a,"func1")) #True
- print(hasattr(a,"func2")) #False
-
- 查看A类是否有s这个方法,返回结果为True或False
-
-
-
- #(3)对已存在的属性进行赋值:
- >>>class A(object):
- ... bar = 1
- ...
- >>> a = A()
- >>> getattr(a, 'bar') # 获取属性 bar 值
- 1
- >>> setattr(a, 'bar', 5) # 设置属性 bar 值
- >>> a.bar
- 5
-
- #如果属性不存在会创建一个新的对象属性,并对属性赋值:
-
- >>>class A():
- ... name = "runoob"
- ...
- >>> a = A()
- >>> setattr(a, "age", 28)
- >>> print(a.age)
- 28
- >>>
-
-
-
-
-
-
-
getattr()调用类里面的方法
hasattr()给类里面添加方法
setattr()查看该类里面是否有该方法