python嵌套类(内部类相互调用)_在python中从内部类访问外部类

本文详细探讨了如何在Python中实现内部类(嵌套类)之间的相互调用以及从外部类访问内部类的方法。通过示例代码展示了如何在外部类的方法中创建和使用内部类,以及如何扩展内部类并保持其与外部类的关联。同时,解释了如何处理内部类的非公共继承问题,并提供了解决方案。
摘要由CSDN通过智能技术生成

也许我很生气,但这看起来确实很简单-问题是让你的内部类在外部类的方法中。。。def do_sthg( self ):

...

def messAround( self ):

outerClassSelf = self

class mooble():

def do_sthg_different( self ):

...

outerClassSelf.do_sthg()

另外……”“self”仅用于约定,因此您可以这样做:def do_sthg( self ):

...

def messAround( outerClassSelf ):

class mooble():

def do_sthg_different( self ):

...

outerClassSelf.do_sthg()

可能会有人反对你不能从外部类创建这个内部类。。。但这不是真的:class Bumblebee():

def do_sthg( self ):

print "sthg"

def giveMeAnInnerClass( outerClassSelf ):

class mooble():

def do_sthg_different( self ):

print "something diff\n"

outerClassSelf.do_sthg()

return mooble

然后,在几英里之外的某个地方:blob = Bumblebee().giveMeAnInnerClass()()

blob.do_sthg_different()

甚至把船推出一点并扩展这个内部类(NB要获得super()才能工作,您必须将mooble的类签名更改为“类mooble(object)”class InnerBumblebeeWithAddedBounce( Bumblebee().giveMeAnInnerClass() ):

def bounce( self ):

print "bounce"

def do_sthg_different( self ):

super( InnerBumblebeeWithAddedBounce, self ).do_sthg_different()

print "and more different"

ibwab = InnerBumblebeeWithAddedBounce()

ibwab.bounce()

ibwab.do_sthg_different()

稍后

mrh1997提出了一个有趣的观点,即使用这种技术交付的内部类的非公共继承。但解决方案似乎非常简单:class Fatty():

def do_sthg( self ):

pass

class InnerFatty( object ):

pass

def giveMeAnInnerFattyClass(self):

class ExtendedInnerFatty( Fatty.InnerFatty ):

pass

return ExtendedInnerFatty

fatty1 = Fatty()

fatty2 = Fatty()

innerFattyClass1 = fatty1.giveMeAnInnerFattyClass()

innerFattyClass2 = fatty2.giveMeAnInnerFattyClass()

print ( issubclass( innerFattyClass1, Fatty.InnerFatty ))

print ( issubclass( innerFattyClass2, Fatty.InnerFatty ))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值