Basic Python

TypeError : Can't instantiate abstract class with abstract method

Naranjito 2022. 6. 29. 16:39
  • abstract class

It is desiged for common methods, forcing its implementation. Using an abstract class causes an error if there is no method in the child class that inherited from abstract class. As a result, the abstract class has many advantages, such as being easy to standardize the program and easy to maintain.

A class which has abstract method. It only declare the abstract method function by pass. 

 

- Steps

1. Get abc module(abstract base class)

2. Create abstract class : Declare metaclass=ABCMeta inside the class

3. Declare abstract method adding @abstractmethod when create the method. These methods are defined but not implemented. The implementation will occur once you create classes that inherit from StudentBase.

 

This is basic frame below.

 

1.
from abc import *

2.
class StudentBase(metaclass=ABCMeta):

or 

class StudentBase():
    __metaclass__=ABCMeta

3.
    @abstractmethod 
    def study(self):
        pass 
    
    @abstractmethod
    def go_to_school(self):
        pass

 

This is embodied abstract class below.

class StudentBase(metaclass=ABCMeta):
    @abstractmethod 
    def study(self):
        pass 
    
    @abstractmethod
    def go_to_school(self):
        pass               

#subclass    
class Student(StudentBase):
    def study(self):
        print('study')
        
joohyun=Student()
joohyun.study()

>>>

...

TypeError: Can't instantiate abstract class Student with abstract method go_to_school

It occurs error because there are two functions(study, go_to_school) under the @abstractmethod. But there is only study method in Student class(inherited StudentBase class).

 

Error fixed below.

class Student(StudentBase):
    def study(self):
        print('study')
        
    def go_to_school(self):
        print('go to school') 
        
joohyun=Student()
joohyun.study()
joohyun.go_to_school()

>>>

study
go to school

 

-TIPS

1. Abstract class cannot create instance. Therefore all the method through 'pass' under @abstractmethod.

2. The class inherited from abstract class needs same functions as abstract class.

'Basic Python' 카테고리의 다른 글

Underscore(_)  (0) 2022.07.05
instancemethod, classmethod, staticmethod  (0) 2022.07.01
title, items  (0) 2022.06.29
tqdm  (0) 2022.04.07
union, intersection  (0) 2022.03.10