PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] When defining class attributes, which method of writing is more "Pythonic"?

 July 08, 2022     class, python     No comments   

Issue

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?


Solution

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.



Answered By - mousetail
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing