【问题标题】:Determine the defining class from within a method从方法中确定定义类
【发布时间】:2016-04-22 16:54:58
【问题描述】:

以下 Python 3.5 代码:

class Base(object):
    def __init__(self):
        print("My type is", type(self))

class Derived(Base):
    def __init__(self):
        super().__init__()
        print("My type is", type(self))

d = Derived()

打印:

My type is <class '__main__.Derived'>
My type is <class '__main__.Derived'>

我想知道,在每个__init__() 中,定义方法的类,而不是派生类。所以我会得到以下打印:

My type is <class '__main__.Base'>
My type is <class '__main__.Derived'>

【问题讨论】:

  • @alecxe 我看到了那个链接,它与我的问题无关,因为 1) Base 和 Derived 都有 init 方法,因此中继名称没有帮助。 2) 我想知道 init 方法中的定义类,以及任何级别的继承。

标签: python inheritance python-3.5


【解决方案1】:

解决方案 1

使用super().__thisclass__:

class Base(object):
    def __init__(self):
        print("My type is", super().__thisclass__)

class Derived(Base):
    def __init__(self):
        super().__init__()
        print("My type is", super().__thisclass__)

d = Derived()

My type is <class '__main__.Base'>
My type is <class '__main__.Derived'>

解决方案 2

类工作没有那么优雅但硬接线:

class Base(object):
    def __init__(self):
        print("My type is", Base)

class Derived(Base):
    def __init__(self):
        super().__init__()
        print("My type is", Derived)

d = Derived()

输出:

My type is <class '__main__.Base'>
My type is <class '__main__.Derived'>

【讨论】:

  • 确实 super().__thisclass__ (解决方案 1)可以解决问题。这正是我所需要的。
猜你喜欢
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 2015-08-25
  • 2014-02-23
  • 2022-01-01
相关资源
最近更新 更多