• Python内部类,内部类调用外部类属性,方法


    一 Python中内部类

    典型定义:

    class MyOuter:
        age=18
        def __init__(self,name):
            self.name=name
    
        class MyInner:
            def __init__(self,inner_name):
                self.inner_name=inner_name
    
    out=MyOuter('lqz')
    inner=out.MyInner('lqz_inner')
    print(inner.inner_name)

    二 内部类调用外部类的属性和方法

    (注意是类属性和类方法,不是对象属性和对象的绑定方法)

    class MyOuter:
        age=18
        def __init__(self,name):
            self.name=name
        @classmethod
        def outer_class_method(cls):
            print('我是外部类的类方法')
    
        class MyInner:
            def __init__(self,inner_name):
                self.inner_name=inner_name
            def inner_method(self):
                print('我是内部类的对象方法')
                MyOuter.outer_class_method()
    
    out=MyOuter('lqz')
    inner=out.MyInner('lqz_inner')
    inner.inner_method()

    三 内部类调用外部对象的对象属性和方法

    需要在内部类构造的时候,把对象传过来

    class MyOuter:
        age=18
        def __init__(self,name):
            self.name=name
        @classmethod
        def outer_class_method(cls):
            print('我是外部类的类方法')
        def outer_obj_method(self):
            print('我是外部类对象的绑定方法')
    
        class MyInner:
            def __init__(self,inner_name,obj):
                self.inner_name=inner_name
                self.obj=obj
            def inner_method(self):
                print('我是内部类的对象方法')
                MyOuter.outer_class_method()
                self.obj.outer_obj_method()
    
    out=MyOuter('lqz')
    inner=out.MyInner('lqz_inner',out)
    inner.inner_method()
  • 相关阅读:
    [LeetCode] Search for a Range
    [C++] extern关键字的作用
    [LeetCode] Sentence Similarity
    [LeetCode] Flood Fill
    [LeetCode] Can Place Flowers
    [LeetCode] Intersection of Two Linked Lists
    [LeetCode] My Calendar II
    [LeetCode] My Calendar I
    [LeetCode] Self Dividing Numbers
    [LeetCode] Range Sum Query
  • 原文地址:https://www.cnblogs.com/liuqingzheng/p/9504210.html
Copyright © 2020-2023  润新知