You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python父类中实现返回子类名称的类方法?

问题:在Python父类中实现返回子类名称的方法

希望在父类中创建方法,使其能够返回子类的名称。尝试了多种方式但未达到预期效果:

尝试1:类方法直接赋值类属性

class TestParentClass():
    somefield = ""
    
    @classmethod
    def get_name(cls):
        class_name = cls.__name__
        return class_name


class TestClass(TestParentClass):
    somefield = TestParentClass.get_name()


print(TestClass().somefield) # 期望输出'TestClass',实际输出'TestParentClass'

尝试2:抽象方法

from abc import abstractmethod

class TestParentClass():
    somefield = ""
    
    @abstractmethod
    def get_name():
        class_name = __class__.__name__
        print(class_name)
        return class_name

实际仍输出TestParentClass。

尝试3:在子类构造函数中调用父类方法

class TestClass(TestParentClass):
    def __init__(self) -> None:
        somefield = TestParentClass.get_name() # 仍然得到'TestParentClass'

想要实现类似以下C#代码的效果:

class TestParentClass
{
    public string SomeField { get; set; }

    public string GetName()
    {
        return this.GetType().Name;
    }
}

class TestClass : TestParentClass
{
    public TestClass()
    {
        SomeField = this.GetName();
    }
}

void Main()
{
    Console.WriteLine(new TestClass().SomeField); // 输出TestClass
}

解决方案

方法1:使用实例方法(对应C#实例方法逻辑)

在父类中定义实例方法,通过self.__class__.__name__获取当前实例所属子类的名称,再在子类构造函数中给实例属性赋值:

class TestParentClass:
    def __init__(self):
        self.somefield = ""  # 定义为实例属性而非类属性
    
    def get_name(self):
        return self.__class__.__name__


class TestClass(TestParentClass):
    def __init__(self):
        super().__init__()
        self.somefield = self.get_name()


print(TestClass().somefield)  # 输出: TestClass

方法2:正确使用类方法

通过实例调用类方法,此时cls会自动绑定到子类:

class TestParentClass:
    @classmethod
    def get_name(cls):
        return cls.__name__


class TestClass(TestParentClass):
    def __init__(self):
        self.somefield = self.get_name()


print(TestClass().somefield)  # 输出: TestClass

方法3:使用@property简化属性获取

如果somefield仅用于存储类名,可直接用属性代替显式赋值:

class TestParentClass:
    @property
    def somefield(self):
        return self.__class__.__name__


class TestClass(TestParentClass):
    pass


print(TestClass().somefield)  # 输出: TestClass

内容的提问来源于stack exchange,提问作者alelom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 03:42:14