[英]Getting name of subclass from superclass?
I have a base class bc
and a number of subclasses based on bc
. 我有一个基类bc
和许多基于bc
的子类。
class bc(Object):
def get_subclass_name(self):
# Retrieve the name of the most derived subclass of this instance
pass
def somemethod(self):
x = self.get_subclass_name()
class sc1(bc):
pass
class sc2(bc)
pass
The idea is that when somemethod()
is invoked on an instance of a subclass of bc
, it will be able to use the name of the most derived subclass of that instance without needing to know in advance what potential subclasses may exist. 我们的想法是,当在bc
的子类的实例上调用somemethod()
时,它将能够使用该实例的派生程度最大的子类的名称,而无需事先知道可能存在哪些子类。
I have put together a test case for this: 我为此编了一个测试用例:
class base_class(object):
@classmethod
def get_subclass_name(cls):
return cls.__name__
def somemethod(self):
print(base_class.get_subclass_name())
class sub_class(base_class):
pass
sub_class().somemethod()
When this code is run it produces base_class
rather than sub_class
. 运行此代码时,它会生成base_class
而不是sub_class
。
Just as an alternative to @poorsod's solution, which works perfectly fine for me, here's another, perhaps simpler variant without class methods, using self.__class__
. 正如@ poorsod的解决方案的替代方案,对我来说非常好,这是另一个,也许更简单的没有类方法的变种,使用self.__class__
。 Just as self
always points to the current instance, self.__class__
always points to the actual class of that instance. 就像self
总是指向当前实例一样, self.__class__
总是指向该实例的实际类 。
class bc(object):
def get_subclass_name(self):
return self.__class__.__name__
Example, tested in Python 2.6.6: 示例,在Python 2.6.6中测试:
>>> class sc1(bc): pass
>>> class sc2(sc1): pass
>>> class sc3(sc2): pass
>>> print sc2().get_subclass_name()
sc2
If this does not work, please be more specific as to what output you expect and what output you are getting instead. 如果这不起作用,请更具体地说明您期望的输出以及您获得的输出。
You need a class method . 你需要一个类方法 。
class bc(Object):
@classmethod
def get_subclass_name(cls):
return cls.__name__
def somemethod(self):
x = self.get_subclass_name()
Normal methods, when invoked, get passed the instance as the first parameter. 调用时,常规方法将实例作为第一个参数传递。 This is why you see self
everywhere in Python. 这就是为什么你在Python中到处看到self
原因。
When you invoke a class method, however, the concrete class of the instance is passed to the function. 但是,在调用类方法时, 实例的具体类将传递给该函数。 We usually use the name cls
, as I have done here. 我们通常使用名称cls
,就像我在这里所做的那样。
The classic use case for class methods is alternative constructors . 类方法的经典用例是替代构造函数 。 For example, the standard library's dict
class provides a fromkeys
class method, which constructs a new dict from the supplied keys and a single value. 例如,标准库的dict
类提供了一个fromkeys
类方法,该方法根据提供的键和单个值构造一个新的dict。 You could construct such a dict manually, but the Python developers made life easy for you! 您可以手动构建这样的dict,但Python开发人员让您的生活变得轻松!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.