Home > Net >  Define a method in one line accesing parent class in Python
Define a method in one line accesing parent class in Python

Time:02-17

Could I call Spyder.paws or Fish.fins just this way? I've seen this post in which they do it by just defining a function, but I wonder if it could just be done in one line by matching parent method to daughter's one.

class LivinBeing:
    def __init__(self):
        self._extremities = None 
    
    @property
    def extremities(self):
        return self._extremities

class Fish(LivinBeing):
    
    def __init__(self):
        super().__init__()
        self._extremities = 2
    
    fins = super().extremities

class Spyder(LivinBeing):
    
    def __init__(self):
        super().__init__()
        self._extremities = 8
        
    paws = super().extremities    

Spyder().paws
>>> 8

CodePudding user response:

You can use the parent class explicitly instead of calling super. paws will be just an alias to extremities in this case:

class Spyder(LivinBeing):
    def __init__(self):
        super().__init__()
        self._extremities = 8
        
    paws = LivinBeing.extremities
Spyder.extremities
# <property at 0x7f46cfbf1d50>
Spyder.paws
# <property at 0x7f46cfbf1d50>
Spyder().paws
# 8
  • Related