Home > Software design >  When defining class attributes, which method of writing is more "Pythonic"?
When defining class attributes, which method of writing is more "Pythonic"?

Time:06-09

I do this fairly frequently, and maybe it's bad design and there's a better way to do it, but I haven't ever had any issue.

When defining an object with a parent and assigning an attribute of that object to an attribute of the parent, which of these methods of writing is more "Pythonic"?

Assuming we are doing something like...

class SomeParent:
    def __init__(self, value):
        self.value = value

class SomeChild { ... }

parentObj = SomeParent(value="foo")
childObj = SomeChild(parent=parentObj)

Would the "proper" way to write the __init__ for SomeChild be...

class SomeChild:
    def __init__(self, parent):
        self.parent = parent
        self.value = parent.value

Or...

class SomeChild:
    def __init__(self, parent):
        self.parent = parent
        self.value = self.parent.value

The only difference being the use of self when defining value on the child object. Obviously, they both (seemingly) work exactly the same, does it even matter which is used? Or am I overthinking this?

CodePudding user response:

You can do this more cleanly with a property:

class A:
    def __init__(self, value):
        self.value = value

class B:
    def __init__(self, a):
        self.a = a

    @property
    def value(self):
        return self.a.value


assert B(A(2)).value == 2

This way, B.value will automatically update with a.value.

Note: I purposefully don't use the names "parent" and "child" which would imply inheritence. You are not using inheritence.

  • Related