Is this possible?

Question:

In python 2.6 and up, is is possible to do something like C#’s

IFoo f= new Foo.
Asked By: Levi Campbell

||

Answers:

Python is a strongly, dynamically typed language. What this means is:

  • Objects are strongly typed which means an integer is an integer and can’t be treated as anything else unless you say so. Objects have a specific type and stay that way.
  • You can use a name (a variable) to refer to an object, but the name doesn’t have any particular type. It all depends on what the name refers to, and this can change as other things are assigned to the same name.

Python strongly makes use of the so-called “duck typing” technique where objects do not have (and do not need) specifically typed interfaces. If an object supports a certain set of methods (the canonical example is a file-like object), then it can be used in a context that expects file-like objects.

Answered By: Greg Hewgill

According to your question, it looks that you want an instance of IFoo that may act like Foo. Following code does that, but its not recommended to do it that way in Python.

class IFoo(object): pass
class Foo(IFoo): pass

f = IFoo()
Foo.__init__(f)

Better way is to simply use (multi)inheritance:

class IFoo(object):
    def __init__(self, *args, **kwargs):
        pass

class Foo(IFoo):
    def __init__(self, *args, **kwargs):
        IFoo.__init__(self, *args, **kwargs)

f = Foo()
Answered By: mtasic85
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.