Python:如何在基类的方法中获取子类的新属性名称? [英] Python: how to get subclass's new attributes name in base class's method?

查看:463
本文介绍了Python:如何在基类的方法中获取子类的新属性名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将SubClass中的所有属性名称都放到一个列表中,我想在Base类中这样做.我怎样才能做到这一点? 我现在的方法是:

I want to put all attribute names in SubClass to a list, I want to do that in Base class. How can I do that? My method now is:

class Base():
    def __init__(self):
        # print SubClass' new attribues' names ('aa' and 'bb' for example)
        for attr in dir(self):
            if not hasattr(Base, attr):
                print attr

class SubClass(Base):
    aa = ''
    bb = ''

有更好的方法吗?

感谢您的帮助.

推荐答案

正如@JohnZwinck在评论中建议的那样,如果需要这样做,几乎可以肯定会犯一个设计错误.但是,如果没有更多信息,我们将无法诊断问题.

As the @JohnZwinck suggested in a comment, you're almost certainly making a design mistake if you need to do this. Without more info, however, we can't diagnose the problem.

这似乎是您想要做的最简单的方法:

This seems the simplest way to do what you want:

class Base(object):
    cc = '' # this won't get printed
    def __init__(self):
        # print SubClass' new attribues' names ('aa' and 'bb' for example)
        print set(dir(self.__class__)) - set(dir(Base))

class SubClass(Base):
    aa = ''
    bb = ''


foo = SubClass()
# set(['aa', 'bb'])

您需要self.__class__而不是self来测试新属性的原因是:

The reason you need self.__class__ instead of self to test for new attributes is this:

class Base(object):
    cc = ''
    def __init__(self):
        print set(dir(self)) - set(dir(Base))
        # print SubClass' new attribues' names ('aa' and 'bb' for example)

class SubClass(Base):
    def __init__(self):
        self.dd = ''
        super(SubClass, self).__init__()
    aa = ''
    bb = ''


foo = SubClass()
# set(['aa', 'dd', 'bb'])

如果您希望定义的类之间存在差异,则需要使用__class__.如果不这样做,根据您何时检查新属性,您会得到不同的结果.

If you want the difference between the classes as defined, you need to use __class__. If you don't, you'll get different results depending on when you check for new attributes.

这篇关于Python:如何在基类的方法中获取子类的新属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆