Scribbling

Python: ABC Class 본문

Computer Science/Python

Python: ABC Class

focalpoint 2022. 4. 7. 12:07

 

The main goals we use 'Abstract Base Class' in python are as follows:

- to provide a standerdized way to test whether an object adheres to a certain specification

- to prevent any attempt to initiate a subclass that does not override methods of the super class

 

1> To provide a standerdized way to test whether an object adheres to a certain specification


import abc

class TypeGroup1(metaclass=abc.ABCMeta):
    pass

@TypeGroup1.register
class UniqueObject:
    pass

TypeGroup1.register(list)
TypeGroup1.register(tuple)


def iamfunc(object):
    if isinstance(object, TypeGroup1):
        print("Passed object is in TypeGroup1")
    else:
        print("None")

iamfunc([])
iamfunc((3, 4))
iamfunc(UniqueObject())
iamfunc(dict())

 

2> To prevent any attempt to initiate a subclass that does not override methods of the super class

import abc

class Abstract(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def func(self):
        pass

class Derived1(Abstract):
    def func(self):
        pass

class Derived2(Abstract):
    pass

d = Derived1()
d = Derived2()

Among many advantages of using it, the program raises error during import time can be especially helpful.

'Computer Science > Python' 카테고리의 다른 글

Python: Inheritance  (0) 2022.04.19
Python: Interfaces  (0) 2022.04.18
Python: Sequence Protocol  (0) 2022.04.06
Python: Pythonic Object  (0) 2022.04.05
Python: Object References  (0) 2022.04.04