Movatterモバイル変換
[0]ホーム
[Python-ideas] Fwd: Define a method or function attribute outside of a class with the dot operator
Steve Dowersteve.dower at python.org
Fri Feb 10 15:42:54 EST 2017
On 10Feb2017 1400, Stephan Hoyer wrote:> An important note is that ideally, we would still have way of indicating> that Spam.func should exists in on the Spam class itself, even if it> doesn't define the implementation. I suppose an abstractmethod> overwritten by the later definition might do the trick, e.g.,>> class Spam(metaclass=ABCMeta):> @abstractmethod> def func(self):> pass>> def Spam.func(self):> return __class__An abstractfunction should not become a concrete function on the abstract class - the right way to do this is to use a subclass.class SpamBase(metaclass=ABCMeta): @abstractmethod def func(self): passclass Spam(SpamBase): def func(self): return __class__If you want to define parts of the class in separate modules, use mixins:from myarray.transforms import MyArrayTransformMixinfrom myarray.arithmetic import MyArrayArithmeticMixinfrom myarray.constructors import MyArrayConstructorsMixinclass MyArray(MyArrayConstructorsMixin, MyArrayArithmeticMixin, MyArrayTransformMixin): passThe big different between these approaches and the proposal is that the proposal does not require both parties to agree on the approach. This is actually a terrible idea, as subclassing or mixing in a class that wasn't meant for it leads to all sorts of trouble unless the end user is very careful. Providing first-class syntax or methods for this discourages carefulness. (Another way of saying it is that directly overriding class members should feel a bit dirty because it *is* a bit dirty.)As Paul said in an earlier email, the best use of non-direct assignment in function definitions is putting it into a dispatch dictionary, and in this case making a decorator is likely cleaner than adding new syntax.But by all means, let's have a PEP. It will simplify the discussion when it comes up in six months again (or whenever the last time this came up was - less than a year, I'm sure).Cheers,Steve
More information about the Python-ideasmailing list
[8]ページ先頭