0

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.

7
  • literally just return dir(MyClass), what else do you need? Commented Dec 19, 2024 at 9:19
  • @ŁukaszKwieciński cannot reproduce. Running your suggested code returns a list of class methods ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_all_attr'] But it doesn't return 'a' and 'b' which is what the OP asked. Commented Dec 19, 2024 at 9:22
  • 2
    Attributes can be added dynamically, not only by the constructor, and not only at instance creation time. They can be different (number of) attributes on different instances, so which of those variations do you want your static method to report on, even when you don't have any instances yet? This is not well-defined. You'll need to add clarification to remove any such ambiguity. Commented Dec 19, 2024 at 9:45
  • At the very least, why would this be a static method, rather than a class method? Commented Dec 19, 2024 at 14:12
  • @chepner good point, I changed it Commented Dec 19, 2024 at 14:22

1 Answer 1

-3
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)
Sign up to request clarification or add additional context in comments.

1 Comment

Just a code block dump without any explanation how this answers the question is not helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.