Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract classes with varying amounts of parameters

I was wondering if its possible when creating an abstract class with abstract methods if its possible to allow the implementations of those methods in the derived classes to have different amounts of parameters for each function.

I currently have for my abstract class

from abc import ABCMeta, abstractmethod  class View(metaclass=ABCMeta):     @abstractmethod     def set(self):         pass      @abstractmethod     def get(self):         pass 

But I want to be able to implement it in one class with set having 1 parameter and get having 2 (set(param1) and get(param1, param2)), and then in another class also inherit it but have 0 parameters for set and 2 for get (set() and get(param1, param2)).

Is this possible and if so how would I go about doing it

like image 998
1seanr Avatar asked Mar 14 '17 06:03

1seanr


People also ask

Can abstract methods have different parameters?

Yes, we can provide parameters to abstract method but it is must to provide same type of parameters to the implemented methods we wrote in the derived classes.

Can abstract class be used as a parameter type?

An abstract class shall not be used as a parameter type, as a function return type, or as the type of an explicit conversion. Pointers and references to an abstract class can be declared.

Can abstract classes contain variables?

Abstract classes can have instance variables (these are inherited by child classes). Interfaces can't. Finally, a concrete class can only extend one class (abstract or otherwise). However, a concrete class can implement many interfaces.

Can abstract method have parameters in Python?

The semantics of an abstract method almost always include the parameters it should take.


Video Answer


1 Answers

No checks are done on how many arguments concrete implementations take. So there is nothing stopping your from doing this already.

Just define those methods to take whatever parameters you need to accept:

class View(metaclass=ABCMeta):     @abstractmethod     def set(self):         pass      @abstractmethod     def get(self):         pass   class ConcreteView1(View):     def set(self, param1):         # implemenation      def get(self, param1, param2):         # implemenation   class ConcreteView2(View):     def set(self):         # implemenation      def get(self, param1, param2):         # implemenation 
like image 114
Martijn Pieters Avatar answered Sep 24 '22 19:09

Martijn Pieters