Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement virtual methods in Python?

I know virtual methods from PHP or Java.

How can they be implemented in Python?

Or have I to define an empty method in an abstract class and override it?

like image 765
Meloun Avatar asked Jan 17 '11 14:01

Meloun


People also ask

How are virtual functions implemented in Python?

Actually, in version 2.6 python provides something called abstract base classes and you can explicitly set virtual methods like this: from abc import ABCMeta from abc import abstractmethod ... class C: __metaclass__ = ABCMeta @abstractmethod def my_abstract_method(self, ...):

Can you implement a virtual method?

Also, you can have an implementation in a virtual method, i.e., virtual methods can have implementations in them. These implementations can be overridden by the subclasses of the type in which the virtual method has been defined.

Is there a virtual function in Python?

Python does not have the concept of virtual function or interface like C++. However, Python provides an infrastructure that allows us to build something resembling interfaces' functionality – Abstract Base Classes (ABC).

How do you create a virtual method?

A virtual method is first created in a base class and then it is overridden in the derived class. A virtual method can be created in the base class by using the “virtual” keyword and the same method can be overridden in the derived class by using the “override” keyword.


1 Answers

Sure, and you don't even have to define a method in the base class. In Python methods are better than virtual - they're completely dynamic, as the typing in Python is duck typing.

class Dog:   def say(self):     print "hau"  class Cat:   def say(self):     print "meow"  pet = Dog() pet.say() # prints "hau" another_pet = Cat() another_pet.say() # prints "meow"  my_pets = [pet, another_pet] for a_pet in my_pets:   a_pet.say() 

Cat and Dog in Python don't even have to derive from a common base class to allow this behavior - you gain it for free. That said, some programmers prefer to define their class hierarchies in a more rigid way to document it better and impose some strictness of typing. This is also possible - see for example the abc standard module.

like image 170
Eli Bendersky Avatar answered Oct 11 '22 13:10

Eli Bendersky