Using custom classes as properties of another class' definition

Advertisements

While I have some Python experience, I’m coming from a mainly Java background for object-oriented programming. Thus, I’m used to declaring variable types.

For simplicity, say I’m creating classes A and B, both of which have their own functions. I’d like to use A as one of the class properties for B. Therefore, upon creating A and B, I can call the methods for object B, and object A which is part of B. I’ve included a sample code below.

While this code works, I am concerned that it may not be the proper way to do so. In Java, I would be able to declare the variable type for the input to class B and I would move on. However, I haven’t been able to figure out the proper implementation for this in Python.

class A:
    def __init__(self,aa):
        self.aa = aa

    def fun(self):
        print(self.aa)

class B:
    def __init__(self,a): # a is an A Object
        self.a = a

    def fun(self):
        print(self.a.aa + 1)

a = A(1)
b = B(a)
b.fun()
b.a.fun()

  • Having the two classes/objects separate help make the code more readable as the classes directly correspond to the physical machinery the program is meant to control. This is why I’m not using parent/child classes.

  • Putting everything within one all-encompassing class isn’t feasible as classes A and B are not being initialized at the same time. This is also why I cannot use a subclass.

  • Aside from the program crashing if the wrong object type is passed into B, I am also not getting the auto-complete suggestions in VS Code for the properties and methods of class A when referencing them within class B (i.e. typing "self.a.aa"). This is a significant inconvenience as there are a significant number of properties and functions in both classes.

>Solution :

A workaround to get appropriate autocomplete suggestions is to use type hinting. You need to import the typing module then alter the init function for B to tell it a is expected to be an A:

import typing
...
class B:
    def __init__(self, a: A):
        ...

VS code will then understand that if b is a B then b.a is an A and offer to autocomplete b.a‘s instance variables and methods.

The type hints are just that – hints – and using something of the wrong type in the B constructor won’t cause an error at compile time. If you want to handle the case when the wrong kind of argument is supplied, you can use isinstance(a, A) to test if a is an A.

Leave a ReplyCancel reply