On 03/25/2018 11:17 AM, Chris Angelico wrote:
On Sun, Mar 25, 2018 at 8:37 PM, Jugurtha Hadjar
<jugurtha.had...@gmail.com> wrote:
On 03/24/2018 07:14 PM, D'Arcy Cain wrote:
class C1(dict):
    class C2(object):
      def f(self):
        return X['field']

O1 = C1()
O1['field'] = 1
O2 = O1.C2()
print(O2.f())

I prefer to *feed* the child to the parent or vice versa.
Congrats, this ranks on my list of "creative people who sound like
psycho murderers". Digital artists and cooks tend to rank fairly
highly on that list.

Given that without prior knowledge, Python may suggest a satirical show or a huge snake, I'm right at home as either creative or a psycho.

class C1(object):
     def __init__(self):
         self.child = None
class C2(object):
     def __init__(self, parent=None):
         self.parent = parent
The trouble with this is that there's fully-constructed objects with
no parent-child relationships. Why should you have a two-step
construction process? It makes a LOT more sense to simply require a
parent on construction, rather than feeding one to the other in a
post-construction assignment. And if you remove the default here, your
suggestion isn't materially different from what's already been posted.


Right, I see.. What do you think about something like this:

<----------------------------------------------------------------------->

class C2(object):
    def __init__(self, parent=None):
        self.parent = parent

    def foo(self):
        print("I am {self.__class__.__name__} foo".format(self=self))
        self.parent.foo()


class C1(object):
    def __init__(self, child_class=None):
        self.child = child_class(parent=self)

    def foo(self):
        print("I am {self.__class__.__name__} foo".format(self=self))

c1 = C1(child_class=C2)
c1.child.foo()  # I am C2 foo
                # I am C1 foo

<------------------------------------------------------------------------>


Check my logic: The reason I'm going through these contortions is to allow the user to choose which child class to use instead of hard coding C2 inside C1, hence the psycho feeding/injecting of C2 in C1. I can delay making a choice and I can even postpone it to run-time (say I have a web-page with a menu that asks which child class I want to use, I can select C2, or C1 and I'll have the instance created with my choice).

Does this make sense and is there a more succinct way to do it this way?

--
~ Jugurtha Hadjar,

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to