一 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()
REF
https://blog.csdn.net/qq_42721964/article/details/85044615