Reputation: 21
I want to be able to call a static method of a class (or classmethod) to only get the attributes of that class. By the attributes of the class, I mean the ones that are set in the constructor of the class. I also use inheritance, so I would like to be able to do this for both MyClass and MyChildClass.
class MyClass():
def __init__(self, x = None, y = None):
self.a = x
self.b = y
@classmethod
def get_all_attr(cls):
return ?
class MyChildClass():
def __init__(self, z = None, **kwargs):
self.c = z
super().__init__(**kwargs)
>>> MyClass.get_all_attr()
['a', 'b']
>>> MyChildClass.get_all_attr()
['c', 'a', 'b']
I know that __dir__()
exists, but I have not been able to call this statically. I've also tried MyClass.__dict__().keys()
, but this also won't work.
Upvotes: 0
Views: 72
Reputation: 1
class MyClass:
attribute1 = "Value1"
attribute2 = "Value2"
@staticmethod
def get_attributes():
return {attr: value for attr, value in MyClass.__dict__.items() if not attr.startswith('__') and not callable(getattr(MyClass, attr))}
# Calling the static method to get the attributes
attributes = MyClass.get_attributes()
print(attributes)
Upvotes: -3