获取类变量驻留在

可以说我有这样的事情 -

class A(object):
    c = C()

class B(A):
    pass

class C(object):
    def __init__(self):
        pass

    def get_parent_class(self):
        # This should return B

我将如何实现get_parent_class ,以便它能够如下工作 -

B.c.get_parent_class() # Returns the class type B (not the instance b!)

这甚至有可能吗?

我基本上有一个父类(在我们的例子中是类A ),它包含一个变量(例子中的var c )。 然后我有一个孩子班(继承A B班)

我想使用C暴露在B上的函数,但为了正确使用,我需要C知道它在B上运行

(希望我没有在最后的解释中使事情复杂化......)

编辑 -请注意,我没有试图获得C类,这是一个简单的c.__class__ 。 我需要持有c的班级

谢谢!


AFAIK,你不能那样做。

Bc只是返回一个对C对象的引用。 同一个对象可以是列表的成员,另一个类的实例(比如D)和另一个类的实例(比如E)

只需添加你的例子:

class D:
    def __init__(self, c):
        self.c = c
class E:
    c = C()

然后 :

>>> c = B.c
>>> E.c = c
>>> d = D(c)
>>> c.a = 1
>>> B.c.a
1
>>> d.c.a
1
>>> E.c.a
1

那时,c对象本身并不知道它属于B,d和E.那么c.get_parent_class()应该返回什么? 如何决定B和E?

你可以试着让C知道它的容器:

class C(object):
    def __init__(self, clazz):
        self.clazz = clazz

    def get_parent_class(self):
        return self.clazz

class A(object):
    c = C(A)

你会得到Acget_parent_class()给出<class '__main__.A'>但是因为它是同一个对象, Bcget_parent_class()也会给出<class '__main__.A'> ...


你可以看看你的对象的__bases__属性。 它返回一个对象的基类的元组。

你可以在这里的文档中看到它。


您可以从name属性中获取该类,例如:

>>> import itertools
>>> x = itertools.count(0)
>>> x.__class__.__name__
'count'

或者这样:

>>> type(x).__name__
'count'
链接地址: http://www.djcxy.com/p/40955.html

上一篇: Getting the class a variable resides in

下一篇: Get model name from instance