pythonoop

Do I have to define attributes in the base class in Python?


This is kind of a "best practices" question, but my IDE is throwing a warning at me when I commit my code, and I'm not sure how to proceed.

"Unresolved attribute reference "attribute" for class "BaseClass".

Essentially I have a base class, with get and set methods.

class BaseClass(object):
    def __set__(self, obj, value):
        foo = obj.bar
        foo.findmethod(self.attribute).setmethod(value)

Then, I inherit from this class when using actual classes I will use:

class ChildClass1(BaseClass):
    attribute = this

class ChildClass2(BaseClass):
    attribute = that

As I will never use the base class directly, I don't see a reason to define this attribute at that level. But the warning makes me wonder if this is bad practice.

Apologies if my naming convention is confusing.


Solution

  • I agree with @jonrsharpe, but not only in the way of workaround, but as a general practice. I think it serves very well to self-documentation and code readability to define the attributes that you set in initializer or elsewhere in instance life, at class-level. Even better if you document them.

    class BaseClass(object):
    
        attribute = None
        '''Should be defined in a subclass. Use for something, here and there.'''
    
    
        def __set__(self, obj, value):
            foo = obj.bar
            foo.findmethod(self.attribute).setmethod(value)