Python Forum

Full Version: Behavior of Abstract Base Class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
All,

Is this behavior correct for ABC class? I expected only the method in class S to be printed. Is this the correct behavior?

import abc 
from abc import ABC, abstractmethod 

class R(ABC): 
	def rk(self): 
		print("Abstract Base Class") 

class K(R): 
	def rk(self): 
		super().rk() 
		print("subclass ") 
        
class S(K):
    def rk(self):
        super().rk()
        print("Class S")

# Driver code 
 
t = S()
t.rk()

'''
This prints

Abstract Base Class
subclass
Class S

'''
All the Best,
David
You are not using ABC at all. If you want to see why someone thought Python needed abstract base classes read the PEP https://www.python.org/dev/peps/pep-3119/

For your example it makes no difference what is the base class of R.
class CBC():
    pass
 
class R(CBC): 
    def rk(self): 
        print("R") 
 
class K(R): 
    def rk(self): 
        super().rk() 
        print("K") 
         
class S(K):
    def rk(self):
        super().rk()
        print("S")
 
# Driver code 
  
t = S()
t.rk()
Output:
R K S
Why did you not expect S.rk() to call K.rk() when it the method calls super().rk()? What did you expect to happen? What problem are you trying to solve that made you look at using abstract base classes?
Thank you. I read the PEP https://www.python.org/dev/peps/pep-3119/ and it answered my question. I was not seeing the super() clear enough.

I don't have a particular use case for using abstract base classes. One reason for ABC e.g., someone who wants to define a generic function (PEP 3124) for any sequence that has an append() method. Python is very extensible. Worth the time. Thanks.

Best,
Dave
I did learn new stuff about usage and what Abstract Base Classes are all about lookin at:
Raymond Hettinger «Build powerful, new data structures with Python's abstract base classes»
@snippsat It is really a very good talk. He has a deep understanding of the software.