简体   繁体   中英

How to force a python class to have a CLASS property? (not a INSTANCE property!!!)

I have googled around for some time, but what I got is all about INSTANCE property rather than CLASS property. For example, this is the most-voted answer for question from stackoverflow

class C(ABC):
    @property
    @abstractmethod
    def my_abstract_property(self):
        return 'someValue'

class D(C)
    def my_abstract_property(self):
        return 'aValue'

class E(c)
   # I expect the subclass should have this assignment,
   # but how to enforce this?
   my_abstract_property = 'aValue'  

However, that is the INSTANCE PROPERTY case, not my CLASS PROPERTY case. In other words, calling
D.my_abstract_property will return something like <unbound method D.my_abstract_property> . Returning 'aValue' is what I expected, like class E.

Based on your example and comment to my previous reply, I've structured the following which works with ABC . :

from abc import ABC

class C(ABC):
    _myprop = None

    def __init__(self):
        assert self._myprop, "class._myprop should be set"

    @property
    def myprop(self):
        return self._myprop


class D(C):
    _myprop = None

    def __init__(self):
        super().__init__()


class E(C):
    _myprop = 'e'

    def __init__(self):
        super().__init__()


e = E()
print(e.myprop)

d = D()
print(d.myprop)

You are correct that there is no Python pre-scan that will detect another developer has not assigned a value to a class variable before initializing. The initializer will take care of notifying pretty quickly in usage.

您可以使用@classmethod 装饰器。

I come up with a tricky workaround.

class C(object):
    myProp = None
    def __init__(self):
        assert self.myProp, 'you should set class property "name"'

class D(C):

    def __init__(self):
        C.__init__(self)

class E(C):
    myProp = 'e'
    def __init__(self):
        C.__init__(self)

print(D.myProp)
print(E.myProp)

But it still has some problems:

  1. D.myProp will not raise any exception to warn the developer about the constraint (assigning myProp as its class property), until the developer initialize an instance of his class.
  2. abc module cannot work with this solution, which means loss of lots of useful features of that module

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM