Python内部类调用外部类
Python内部类调用外部类
Python内部类
class MyOuter: trait='cute' def __init__(self,name): self.name=name class MyInner: def __init__(self,inner_name): self.inner_name=inner_name out=MyOuter('small_cat') inner=out.MyInner('cat_inner') print(inner.inner_name)
内部类调用外部类属性与方法
ps:是类属性类方法,不是对象属性与绑定方法
class MyOuter: trait='cute' 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('small_cat') inner=out.MyInner('cat_inner') inner.inner_method()
内部类调用外部类'对象'的对象属性和绑定方法
ps:内部类构造时,将对象传过去
class MyOuter: trait='cute' 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('small_cat') inner=out.MyInner('cat_inner',out) inner.inner_method()