LoginSignup
4
3

More than 5 years have passed since last update.

サブクラスの要素だけを一覧で取得する

Posted at
class Base(object):

    def getAttributeKeys(self):
        """ Baseを継承したクラスで定義された
            要素(メソッドやプロパティ)のキーだけを取得したい
        """


class Child(Base):

    def __init__(self):
        self.hoge = "hoge"

    def fuga(self):
        pass

この適当な例でいうと、

ch = Child()
print(ch.getAttributeKeys())   # >>> ['hoge', 'fuga']

みたいになって欲しい時。

setを使って引き算する

http://stackoverflow.com/questions/7136154/python-how-to-get-subclasss-new-attributes-name-in-base-classs-method
いろいろやり方はあると思いますが、このやり方が個人的に綺麗かと。

Pythonだと集合演算が簡単に利用できるので、これを使って
サブクラスの要素一覧 から 親クラスの要素一覧 を引く
というような形で子クラスの一覧を取得出来ます。

class Base(object):

    def getAttributeKeys(self):
        return set(dir(self.__class__)) - set(dir(Base))

(※ 結果はlistではなくsetになります。)

あれこれ

ch = Child()
keys = getAttributeKeys()


# attributeの値を取得してみる
key = keys[0] # keysの中から好きに選んだとする
attr = ch.getattr(self, key)


# メソッドかどうかを判定して実行
import types
if isinstance(attr, types.MethodType):
    # attrはメソッドなので実行可能
    attr()

サブクラスで定義したものを自動的に取り込みたい時とかにどうぞ。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3