特殊方法补充,callable 可调用

一.特殊方法补充(__dict__)

 1. 把对象中的变量

class Foo(object):
def __init__(self,name,age):
self.name = name
self.age = age

def func(self):
pass

obj1 = Foo('刘博文',99)
obj2 = Foo('史雷',89)


print(obj1.__dict__) # {'name': '刘博文', 'age': 99}
print(obj2.__dict__) # {'name': '史雷', 'age': 89}

2.把不可迭代对象转换成可迭代对象
  (1)在类中定义__iter__方法
  (2)iter内部返回一个迭代器(生成器也算迭代器)
class Foo(object):
def __init__(self,name,age):
self.name = name
self.age = age

def func(self):
pass

def __iter__(self):
return iter([11,22,33,44,55,66])

yield 11
yield 22
yield 33
obj1 = Foo('刘博文',99) #可迭代

for item in obj1:
print(item)



__repr__方法  类似__str__方法


二.callable能否被调用
def func():
    pass
class Foo(object):
    def __call__(self, *args, **kwargs):
        pass
    def func(self):
        print("a")
obj = Foo()
print(func)


print(callable(func)) #True  (有函数func)
print(callable(Foo))   #True  (类可以调用)
print(callable(obj))   #True   (类中有__call__方法)
print(callable(obj.func))  #True   (类中有func方法)

 







posted on 2018-08-30 16:23  阳景♡  阅读(32)  评论(0)    收藏  举报

导航