python--__call__、__doc__、__str__

__call__

__call__方法:对象后面加括号,触发执行

注:构造方法的执行是由创建对象触发的,即,对象=类名();而对于__call__方法的执行是由对象后加括号执行的,即对象()或者 类()()

class A:
    def __call__(self, *args, **kwargs):
        print('执行call方法了')


class B:
    def __init__(self, cls):
        print('在实例化A之前做一些事情')
        self.a = cls()
        self.a()
        print('在实例化A之后做一些事情')


a = A()
a()  # 对象() == 相当于调用__call__方法
A()()  # 类名()() ,相当于先实例化得到一个对象,再对对象(),==>和上面的结果一样,相当于调用__call__方法
B(A)

结果:

执行call方法了
执行call方法了
在实例化A之前做一些事情
执行call方法了
在实例化A之后做一些事情

class Dog(object):
    name = '金三胖'

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

    def eat(self):
        print('%s is eating %s' %
              (self.name, self.food))

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

    def __call__(self, *args, **kwargs):
        print('in the call...', args, kwargs)


d = Dog('叶良辰', '鸡蛋')
d(666, 'zou', name='王思聪')

Dog('叶良辰', '鸡蛋')(666, 'zou', name='王思聪')

结果:

in the call... (666, 'zou') {'name': '王思聪'}
in the call... (666, 'zou') {'name': '王思聪'}

__doc__

__doc__方法:打印出类下的说明,只能在类下面

class Dog(object):
    '''描述狗的信息'''
    name = '金三胖'

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

    def eat(self):
        print('%s is eating %s' %
              (self.name, self.food))

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


print(Dog.__doc__)

结果:

描述狗的信息

__str__

__str__ 如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。

class Foo(object):

    def __str__(self):
        return 'zouzou'

    def eat(self):
        print('we are eating...')


obj = Foo()
print(obj)

结果:

zouzou

class Student:
    def __str__(self):
        return '%s %s %s' % (self.school, self.cls, self.name)

    def __init__(self, name, stu_cls):
        self.school = 'cxsz'
        self.name = name
        self.cls = stu_cls


z = Student('zou', '2')
print(z)

结果:

cxsz 2 zou

  

原文地址:https://www.cnblogs.com/zouzou-busy/p/13021977.html