简体   繁体   中英

Set attribute of subclass in method of super class

I have the following scenario:

class Baseclass(object):
    extra_fields = []
    @classmethod
    def extend(cls, key):
        cls.extra_fields.append(key)

class A(Baseclass):
    pass

class B(Baseclass):
    pass

A.extend("foo")

Now, extend of Baseclass will be called, setting Baseclass.extra_fields to ["foo"] . Then, A.extra_fields will be ["foo"] , however so will B.extra_fields .

Is there a way in extend to only modify only the subclass on which it was invoked (without defining extend on all subclasses, as those may not be known in advance)?

class Baseclass(object):    
    @classmethod
    def extend(cls, key):
        if not 'extra_fields' in cls.__dict__:
            cls.extra_fields=[]
        cls.extra_fields.append(key)   

class A(Baseclass):
    pass

class B(Baseclass):
    pass

A.extend("foo")

How about defining own extra_fields for each subclass?

class Baseclass(object):
    @classmethod
    def extend(cls, key):
        cls.extra_fields.append(key)

class A(Baseclass):
    extra_fields = []

class B(Baseclass):
    extra_fields = []

A.extend("foo")

(You can automate that with some metaclasses magic as well.)

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