-2

My task is to rewrite app written in Java using Python. It is my first contact with Python and I'm a bit confused. As I read, Python is not strongly typed. In my program I have a lot of classes with methods with parameters which are instances of other classes. Here is a short demo:

class ClassA:

    nameOfClass = "ClassA"

    def __init__(self):
        print("I'm ClassA")

    def printOtherClassMethod(self, instanceOfOtherClass):
        instanceOfOtherClass.printThisMethod()


class ClassB:
    nameOfClass = "ClassA"

    def __init__(self):
        print("I'm ClassB")

    def printThisMethod(self):
        print("How classA can know that printThisMethod exists?")


classA = ClassA()
classB = ClassB()
classA.printOtherClassMethod(classB)

Is there any way to specify that argument of printOtherClassMethod must be instance of ClassB? The first problem is that my IDE (PyCharm) can't detect that instanceOfOtherClass has printThisMethod and it is very easy to make mistake. Additionally, I have a practise to have each class in the individual file. I'm afraid of importing particular files. For example if ClassA and ClassB would be in individual files should I import ClassB in file of ClassA? My tests show that not, but I want to avoid milions of exceptions and error in the future.

SigGP
  • 716
  • 1
  • 11
  • 24
  • 2
    Python is strongly typed. An `int` is an `int`. – Peter Wood Jun 03 '17 at 21:12
  • 1
    Python does not use static type declarations. If you want to tell your IDE about the expected types of arguments, use documentation comments. PyCharm has automated tools for creating them, see https://www.jetbrains.com/help/pycharm/2017.1/documenting-source-code-in-pycharm.html – Barmar Jun 03 '17 at 21:17
  • 1
    Python is a strongly typed language with duck typing. You can read more about duck typing here https://stackoverflow.com/questions/4205130/what-is-duck-typing – Will Da Silva Jun 03 '17 at 21:20

1 Answers1

1

You can validate the type of the object.

if type(instanceOfOtherClass) not is ClassB:
    raise Exception("Object has the wrong type.")

You can also check that the object has that particular method.

if not (hasattr(instanceOfOtherClass, 'printThisMethod') and callable(instanceOfOtherClass.printThisMethod)):
    raise Exception("Object does not have the correct method.")
J. Darnell
  • 519
  • 7
  • 15
  • 1. Classes are singleton, that should be `is not`. 2. You shouldn't compare the class at all as it doesn't work with inheritance, use `isinstance`. 3. `hasattr` doesn't necessarily work with dynamic attributes, you should use EAFP/duck typing. 4. Never raise `Exception`; that's less useful than if you'd left out the checks and let the code fail for itself. – jonrsharpe Jun 04 '17 at 07:18