class Base(object):
def getAttributeKeys(self):
"""Defined in a class that inherits Base
element(Methods and properties)I want to get only the key of
"""
class Child(Base):
def __init__(self):
self.hoge = "hoge"
def fuga(self):
pass
In this suitable example,
ch = Child()
print(ch.getAttributeKeys()) # >>> ['hoge', 'fuga']
When you want to be like.
http://stackoverflow.com/questions/7136154/python-how-to-get-subclasss-new-attributes-name-in-base-classs-method I think there are various ways to do it, but I wonder if this way is personally beautiful.
Set operations are easy to use in Python, so use this
Subclass element list minus parent class element list
You can get a list of child classes like this.
class Base(object):
def getAttributeKeys(self):
return set(dir(self.__class__)) - set(dir(Base))
(* The result will be set instead of list.)
ch = Child()
keys = getAttributeKeys()
#Try to get the value of attribute
key = keys[0] #Suppose you choose from the keys
attr = ch.getattr(self, key)
#Determine if it is a method and execute
import types
if isinstance(attr, types.MethodType):
#Since attr is a method, it can be executed
attr()
Please use it when you want to automatically import what is defined in the subclass.
Recommended Posts