python 内部类调用外部类变量_嵌套的Python类需要访问封闭类中的变量

小编典典

尽管我发表了“有点光顾”的评论(公平地称呼它!),实际上还是有一些方法可以实现您想要的:继承的另一种途径。一对夫妇:

编写一个装饰器,该装饰器在声明一个类后立即对其进行内省,找到内部类,并将属性从外部类复制到它们中。

用元类做同样的事情。

这是装饰器方法,因为它是最简单的方法:

def matryoshka(cls):

# get types of classes

class classtypes:

pass

classtypes = (type, type(classtypes))

# get names of all public names in outer class

directory = [n for n in dir(cls) if not n.startswith("_")]

# get names of all non-callable attributes of outer class

attributes = [n for n in directory if not callable(getattr(cls, n))]

# get names of all inner classes

innerclasses = [n for n in directory if isinstance(getattr(cls, n), classtypes)]

# copy attributes from outer to inner classes (don't overwrite)

for c in innerclasses:

c = getattr(cls, c)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值