0

I have following structure for my program-

File1.py

class A:
   index1
   def method1():
       // --do stuff--

File2.py

import File1

Class B:
   index2
   def method2(a) // Needs Object of A as a parameter
        // --do stuff--
        a.method1() // How can I guarantee that this is an object of class A

File3.py

import File1
import File2
Class Starter:
   def start():
       a = A()
       b = B()
       b.method2(a)

I have few questions-

  1. How can I ensure that parameter a in method2 is an object of class A?
  2. It might be IDE specific, but can I find out all the methods and variables that I can access in method2 on object 'a' while writing the code?
  3. Is it better to write such object oriented programs in Java rather than python?
1
  • Isn't this the essence of Duck Typing? Commented Mar 15, 2016 at 20:57

3 Answers 3

1

(1) If the parameter for method2 really must be an instance of class A then you can use the isinstance builtin to verify its type. However the pythonic way is simply to assume that the any object will be satisfactory as long as it exposes the methods that class B wants to call. This is what @johnny means by 'duck typing'.

(2) This is generally an IDE thing, but in the interactive interpreter you can call dir() or vars() on the object to inspect its attributes.

(3) It's a matter of taste. Java lets you be confident that an object will behave exactly as expected, at the expense of declaring types, interfaces, checked exceptions etc. Python offers less confidence that the behaviour will be exactly as expected, but you need not spend so much time constructing type hierarchies in advance.

Sign up to request clarification or add additional context in comments.

Comments

1

You can check the type like this:

    import File1

    Class B:
       index2
       def method2(a) // Needs Object of A as a parameter
             // --do stuff--
             // How can I guarantee that this is an object of 
             if type(a) == A:
                 a.method1() 

Comments

0

To guarantee that a parameter is of a given class before performing any task using that parameter, you can use the in-built 'type()' function to verify it first before performing the required task.

Comments

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.