初学python的人,一定会感觉到python中实例属性和函数的用法超级灵活,写这篇也主要是给小白看的,能够快速的掌握py中实例属性和函数的调用方法。
--------------------------------Talk is cheap. Show you the code--------------------------------
接下来请不要错过每一个字.......
- oop包中的obj.py
class Teacher(object):
def __init__(self, name):
self.name = name
self.__other_name = name
self.__book_name__ = name
def jiangke(self):
print("我正在讲课.....")
- module包中的module.py
import pystudy.oop.obj as _obj_
t = _obj_.Teacher("张三")
############属性####################
print(getattr(t, "name")) # 张三 获取实例的属性值
# n = getattr(t, "name") 根本没name这个函数,当然会报错了
# n() # TypeError: 'str' object is not callable
print("我是:", t.name) # 我是: 张三
# print("我的外号:", t.__other_name) # 外号不能让你知道!哈哈 异常: AttributeError: 'Teacher' object has no attribute '__other_name'
print("我的书名:",t.__book_name__) # 我的书名: 张三 可以看到区别只是属性只是后边多俩下划线而已就可以被访问
############函数####################
t.jiangke() # 我正在讲课..... 直接调用实例的函数
jiangke = getattr(t, "jiangke") # 获取函数值
jiangke() # # 我正在讲课..... 直接调用函数
getattr(t, "jiangke")() # 我正在讲课..... 尼玛这也可以