2
from abc import ABC, abstractmethod

class BasketballPlayer(ABC):

    move1 = 'pass'
    move2 = 'dribble'
    move3 = 'shoot'

    @property
    @abstractmethod
    def name(self):
        pass



class Player2(BasketballPlayer):
    def name(self):
        pass


y = Player2()

I expect an error on the line y = Player2() because the name is suddenly declared as a method instead of a property. Is this a bug? or something I did wrong?

Dean Christian Armada
  • 6,724
  • 9
  • 67
  • 116

1 Answers1

0

Equally Python won't care if you implement @abstractmethod as class variable. I am not sure what is logic behind this, perhaps good question to ask on: https://github.com/python/cpython/issues

from abc import ABC, abstractmethod, abstractproperty

class MyAbstractClass(ABC):
    @property
    @abstractmethod
    def name(self):
        pass

    @abstractmethod
    def run(self):
        pass

class Child(MyAbstractClass):
    name = "foo"
    run = "foo"


c = Child()
print(c.name)

I found similar question with answer here: enforcement for abstract properties in python3

Adam
  • 459
  • 2
  • 17
  • `ABCMeta` only cares that some attribute named `name` gets defined; it does not care (in keeping with the dynamic nature of Python) what the *type* of value assigned to `name` will be. `abstractmethod` isn't really a descriptive name, but we're stuck with it, though it at least conveys the *intent*. – chepner Jul 18 '22 at 14:30
  • @chepner Indeed. The thing is that it has not been documented anywhere and might be confusing especially for people coming from stricter languages. – Adam Jul 18 '22 at 14:31
  • 1
    The key line in the documentation is "A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden." You just have to understand that in a dynamically typed language, because the attribute itself is not typed (only the value of the attribute) an override doesn't necessarily preserve the type of the thing being overriden. It could be more explicit, but the official documentation isn't under any obligation to describe things in terms of other languages, only its own model. – chepner Jul 18 '22 at 14:37
  • 1
    The "protection" offered by this implementation of abstract base classes is so easily bypassed that I consider its primary value as a documentation tool. (The only thing you need to do to turn an abstract class into a concrete class is change its `__abstractmethods__` attribute to an empty container. It's all name-based and supported via library code, rather than being an intrinsic part of the language itself.) – chepner Jul 18 '22 at 14:42