Python 类继承之类变量和类方法的用法

本页主要讨论python中的类继承时的类变量和类方法的用法。在阅读相关代码时,一定要切记当前 self 是谁,类型是什么,继承关系是什么,MRO是什么。这样才能准确把握代码的调用流程。

示例代码:注意在类方法 get_name() 对于 Displayer/ MySubClass 的实例会打印不同的值

class Displayer(object):
	name = None

    @classmethod
    def get_name(cls):
        print 'In the get_name:'
        # 对于 Displayer/ MySubClass 的实例会打印不同的值
        print 'cls = {0}, cls.name = {1}'.format(cls, cls.name) 
        return cls.name

    def display(self):
        print 'In the display:'
        print 'type(self) = {0}, self = {1}'.format(type(self), self)
        name = self.get_name()
        print 'name = {0}'.format(name)


class MySubClass(Displayer):
    name = 'robert'

obj1 = Displayer()
obj1.display()
print '------'
obj2 = MySubClass()
obj2.display()

The output is:
    In the display:
    type(self) = <class '__main__.Displayer'>, self = <__main__.Displayer object at 0x0000000001FD44E0>
    In the get_name:
    cls = <class '__main__.Displayer'>, cls.name = None
    name = None
    ------
    In the display:
    type(self) = <class '__main__.MySubClass'>, self = <__main__.MySubClass object at 0x0000000001FE1E48>
    In the get_name:
    cls = <class '__main__.MySubClass'>, cls.name = robert
    name = robert
发布了44 篇原创文章 · 获赞 0 · 访问量 3962

猜你喜欢

转载自blog.csdn.net/cpxsxn/article/details/99637877