绑定方法与非绑定方法||反射||内置方法

在类内部定义的函数,分为两大类

 一:绑定方法:绑定给谁,就应该由谁来调用,就会把调用者当作第一个参数自动传入

  • 绑定到对象的方法:在类内定义的没有被装饰器修饰的
  • 绑定到类的方法:在类的内部定义的被装饰器classmethod修饰的方法

  二:非绑定方法:没有自动传值这么一说,就是类中定义的一个普通工具,对象和类都可以使用

  • 非绑定方法:不与类或者对象绑定
View Code

绑定方法与非绑定方法的应用

View Code

反射

反射:通过字符串映射到对象的属性

class People:
    country = 'china'

    def  __init__(self,name,age):
        self.name = name
        self.age = age

    def talk(self):
        print('%s is talking' %self.name)

obj = People('egon',18)

print(obj.name) # __init__(obj) name是属性,不是字符串
print(obj.talk)

# choice = input('>>:') #choice='name'
# print(obj.choise) #print(obj.'name')

#判断
print(hasattr(obj,'name')) #判断obj.name #本质上是去判断obj.__dict__['name']
print(hasattr(obj,'talk')) #判断obj.talk

# 获取
print(getattr(obj,'namexx',None))
print(getattr(obj,'talk',None))

# 修改|新增
setattr(obj,'sex','male') #obj.sex='male'
print(obj.__dict__)
print(obj.sex)

# 删除
delattr(obj,'age') #del obj.age
print(obj.__dict__)


####类和对象的用法大同小异
# print(getattr(People,'country')) #People.country
View Code

反射的应用

可以用于对用户输入的字符进行判断

用处:接受用户的输入触发对象的某一个方法

总结:通过字符串来访问到对象或类的数据属性和函数属性

class Service:
    def run(self):
        while True:
            inp = input('>>:').strip() #cmd='get a.txt'
            cmds=inp.split() #cmds=['get','a.txt']

            # print(cmds)
            if hasattr(self,cmds[0]): #判断是否有cmd的属性
                func = getattr(self,cmds[0])
                func(cmds)

    def get(self,cmds):
        print('get.....',cmds)

    def put(self,cmds):
        print('set.....',cmds)

obj = Service()
obj.run()
View Code

内置方法

1.isinstance() isinstance(f,Foo) 什么是什么的对象

2.issubclass() issubclass(Foo,Bar) 什么是什么的子类

3.item系列: 把对象做成一个像字典对象那样 像字典对象那样访问数据

  • 查看属性 def __getitem__(self, item):         obj['name'] 触发
  • 设置属性 def __setitem__(self, key, value): obj['sex']='male' 触发
  • 删除属性 def __delitem__(self, key): del     obj['name']

 

class Bar:
    pass
class Foo(Bar):
    pass
f=Foo()
# print(isinstance(f,Foo))
# print(issubclass(Foo,Bar))
# print(issubclass(Bar,Foo))

# item 系列
class Foo:
    def __init__(self,name):
        self.name=name

    def __getitem__(self, item):
        # return self.__dict__[item]  # 若是没有 会报错
        return self.__dict__.get(item)

    def __setitem__(self, key, value):
        self.__dict__[key]=value

    def __delitem__(self, key):
        del self.__dict__[key]

    def __str__(self):
        return '<name:%s>'%self.name

    def __del__(self):
        # self.close()
        print('回收操作系统的 资源')

obj=Foo('alice')
# print(obj.__dict__)
# print(obj.name)
# print(obj['name'])
# obj['name']='aaaa'
# print(obj.__dict__)
# del obj['name']
# print(obj.__dict__)
# obj.sex='12'
# print(obj.__dict__)

# print(obj)

# del obj
# print('---main---')

内置方法
posted @ 2018-03-20 22:16  Mr。yang  阅读(166)  评论(0编辑  收藏  举报