Home > Back-end >  Am I able to call a submethod of a class's attribute from that class using the class as an attr
Am I able to call a submethod of a class's attribute from that class using the class as an attr

Time:11-12

I am very sorry for the confusing title, I did not know how else to phrase the question.

Let's say I have a class, A. It is described as shown:

class A:
    def __init__(self, argument):
        self.value = argument

    def submethod(self, argumentThatWillBeAClass):
        print(dir(argumentThatWillBeAClass))

And then I initialize it as shown below:

classAInstance = A('42.0')

Now, I have a class, B. Let's add a submethod that calls A's submethod with B as an argument.

class B:
    def __init__(self, argumentThatIsAClassAInstance):
        self.classAInstance = argumentThatIsAClassAInstance

    def submethod(self):
        self.classAInstance.submethod(self)

Let's initialize it with classInstance:

classBInstance = B(classAInstance)

My desired result is that all the attributes of B are printed when B.submethod is called. Is this possible, and if not, how would I achieve something like this?

CodePudding user response:

Now, I have a class, B. Let's add a submethod that calls A's submethod with B as an argument.

But that isn't what your code does. On the following line:

 self.classAInstance.submethod(self)

You are calling the method (I don't know what you mean by "sub" method, these are all just normal methods) with *an instance of B, not B.

Two different ways you could do this:

self.classAInstance.submethod(type(self))

Or:

self.classAInstance.submethod(B)

The semantics aren't exactly the same, since the first dynamically retreives the instance, if some other class inherits from B, it will call dir on that class. The second always prints dir(B), regardless of inheritance.

So:

class A:
    def method(self, klass: type) -> None:
        print(dir(klass))

class B:
     def __init__(self, a: A) -> None:
        self.a = a
     def method(self) -> None:
         self.a.method(type(self))

b = B(A())

CodePudding user response:

As one potential solution, you can use inheritance. This allows class B to inherit everything from class A

class A:
    def __init__(self, argument):
        self.value = argument

    def submethod(self, argumentThatWillBeAClass):
        print(dir(argumentThatWillBeAClass))

class B(A):
    def __init__(self, value):
        super().__init__(value)

    def submethod(self, argumentThatWillBeAClass): # You can override the method and do extra code too. 
        super().submethod(argumentThatWillBeAClass) # Calls A's submethod function
  • Related