Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #26455 > unrolled thread

Deciding inheritance at instantiation?

Started byTobiah <toby@tobiah.org>
First post2012-08-03 13:48 -0700
Last post2012-08-07 10:52 -0700
Articles 8 — 6 participants

Back to article view | Back to comp.lang.python


Contents

  Deciding inheritance at instantiation? Tobiah <toby@tobiah.org> - 2012-08-03 13:48 -0700
    Re: Deciding inheritance at instantiation? Terry Reedy <tjreedy@udel.edu> - 2012-08-03 17:55 -0400
      Re: Deciding inheritance at instantiation? Tobiah <toby@tobiah.org> - 2012-08-06 10:42 -0700
    Re: Deciding inheritance at instantiation? Nobody <nobody@nowhere.com> - 2012-08-04 00:52 +0100
    Re: Deciding inheritance at instantiation? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-08-04 01:14 +0000
    Re: Deciding inheritance at instantiation? "Steven W. Orr" <steveo@syslang.net> - 2012-08-03 23:14 -0400
    Re: Deciding inheritance at instantiation? alex23 <wuwei23@gmail.com> - 2012-08-06 19:53 -0700
      Re: Deciding inheritance at instantiation? Tobiah <toby@tobiah.org> - 2012-08-07 10:52 -0700

#26455 — Deciding inheritance at instantiation?

FromTobiah <toby@tobiah.org>
Date2012-08-03 13:48 -0700
SubjectDeciding inheritance at instantiation?
Message-ID<dOWSr.44251$Zl3.41187@newsfe06.iad>
I have a bunch of classes from another library (the html helpers
from web2py).  There are certain methods that I'd like to add to
every one of them.  So I'd like to put those methods in a class,
and pass the parent at the time of instantiation.  Web2py has
a FORM class for instance.  I'd like to go:

	my_element = html_factory(FORM)

Then my_element would be an instance of my class, and also
a child of FORM.

I started messing with decorators, but it became difficult
for me to visualise how to do this.

Thanks!

Toby
   

[toc] | [next] | [standalone]


#26456

FromTerry Reedy <tjreedy@udel.edu>
Date2012-08-03 17:55 -0400
Message-ID<mailman.2917.1344030962.4697.python-list@python.org>
In reply to#26455
On 8/3/2012 4:48 PM, Tobiah wrote:
> I have a bunch of classes from another library (the html helpers
> from web2py).  There are certain methods that I'd like to add to
> every one of them.  So I'd like to put those methods in a class,
> and pass the parent at the time of instantiation.  Web2py has
> a FORM class for instance.  I'd like to go:
>
>      my_element = html_factory(FORM)
>
> Then my_element would be an instance of my class, and also
> a child of FORM.
>
> I started messing with decorators, but it became difficult
> for me to visualise how to do this.

Use type(name, bases, content) for dynamic class creation.

-- 
Terry Jan Reedy

[toc] | [prev] | [next] | [standalone]


#26642

FromTobiah <toby@tobiah.org>
Date2012-08-06 10:42 -0700
Message-ID<SlTTr.22993$z66.19042@newsfe10.iad>
In reply to#26456
On 08/03/2012 02:55 PM, Terry Reedy wrote:
> On 8/3/2012 4:48 PM, Tobiah wrote:
>> I have a bunch of classes from another library (the html helpers
>> from web2py). There are certain methods that I'd like to add to
>> every one of them. So I'd like to put those methods in a class,
>> and pass the parent at the time of instantiation. Web2py has
>> a FORM class for instance. I'd like to go:
>>
>> my_element = html_factory(FORM)
>>
>> Then my_element would be an instance of my class, and also
>> a child of FORM.
>>
>> I started messing with decorators, but it became difficult
>> for me to visualise how to do this.
>
> Use type(name, bases, content) for dynamic class creation.
>

Very cool.  Just what I was after.  Thanks.

Tobiah

[toc] | [prev] | [next] | [standalone]


#26462

FromNobody <nobody@nowhere.com>
Date2012-08-04 00:52 +0100
Message-ID<pan.2012.08.03.23.53.04.844000@nowhere.com>
In reply to#26455
On Fri, 03 Aug 2012 13:48:08 -0700, Tobiah wrote:

> I have a bunch of classes from another library (the html helpers
> from web2py).  There are certain methods that I'd like to add to
> every one of them.  So I'd like to put those methods in a class,
> and pass the parent at the time of instantiation.  Web2py has
> a FORM class for instance.  I'd like to go:
> 
> 	my_element = html_factory(FORM)
> 
> Then my_element would be an instance of my class, and also
> a child of FORM.

You can use type() to create classes dynamically. E.g.:

	class my_base_class(object):
	    # extra methods

	subclasses = {}

	def html_factory(cls, *args, **kwargs):
	    name = "my_" + cls.__name__
	    if name not in subclasses:
	        subclasses[name] = type(name, (cls, my_base_class), {})
	    return subclasses[name](*args, **kwargs)

[toc] | [prev] | [next] | [standalone]


#26464

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2012-08-04 01:14 +0000
Message-ID<501c7787$0$29978$c3e8da3$5496439d@news.astraweb.com>
In reply to#26455
On Fri, 03 Aug 2012 13:48:08 -0700, Tobiah wrote:

> I have a bunch of classes from another library (the html helpers from
> web2py).  There are certain methods that I'd like to add to every one of
> them.  So I'd like to put those methods in a class, and pass the parent
> at the time of instantiation.  Web2py has a FORM class for instance. 
> I'd like to go:
> 
> 	my_element = html_factory(FORM)
> 
> Then my_element would be an instance of my class, and also a child of
> FORM.

I cannot understand what you are actually trying to do here because you 
aren't giving enough information and the description you give is 
misleading. But from what little I can grasp, I think it sounds like an 
unclean, confusing design and you would be better off with either mixins, 
composition, or code injection.

What is html_factory? By the name, it should return some HTML. But you're 
assigning the output to something called "my_element", which suggests it 
is returning only a single element of HTML. To me, I would expect that to 
be a string. Consequently, it isn't clear to me what you actually want, 
and I'm forced to make some wild guesses, and I can see a number of 
different alternative approaches.


=== Mixins ===

You state:

    There are certain methods that I'd like to add to every 
    one of [my classes].  So I'd like to put those methods 
    in a class, and pass the parent at the time of instantiation

Don't pass the utility class at instantiation time. Use it as a mixin 
class.

class UtilityMixin:
    # add "those methods" to this class
    pass


class MyClassA(MyParentClass, UtilityMixin):
    pass

class MyClassB(AnotherClass, UtilityMixin):
    pass

class MyClassC(MyClassB):  # already inherits from UtilityMixin
    pass


=== Composition ===


This frankly sounds like an abuse of inheritance. Inheritance is for 
modelling "is-a" relationships, not just for sticking arbitrary lumps of 
unrelated code together. If I can understand what you are trying to do, 
then you need to model a "has-a" relationship. For example:

The Contact Us page is not a html form, it HAS a html form;

therefore the instance which creates the Contact Us page is not a html 
form either, and should not inherit from FormClass;

but it should have a FormClass instance it can delegate the creation of 
the form to.


Something like this, perhaps:

contact_page_designer = PageDesigner()
contact_page_designer.form_designer = FormClass()


This can be wrapped inside the __init__ method, of course. The FormClass 
instance can be passed as a generic argument.

Then, your PageDesigner methods which need to create a form simply 
delegate the work to the form_designer attribute. Instead of this:

self.make_form()

which depends on self having ten different methods to do with making 
forms, you do this:

self.form_designer.make_form()

and all the form-related methods are encapsulated in one place, out of 
the way. This general technique is known as composition, or delegation, 
and you use it every time you do something like this:

result = self.name.upper()  # delegating upper method to the string name

And yet, somehow people forget it in favour of inheritance once they move 
beyond the primitive built-in types.


=== Code injection ===

You talk about deciding inheritance at instantiation time, which implies 
that each instance will get different methods. If so, then so long as you 
aren't changing dunder methods (double leading and trailing underscore 
special methods like __init__ and friends), you can inject methods 
directly onto an instance, either to add new functionality or override 
existing functionality on a per-instance basis.


py> class Parrot:
...     def speak(self):
...             print "Polly wants a cracker!"
...
py> class KillBot:
...     def speak(self):
...             print "Crush! Kill! Destroy!"
...
py> p = Parrot()
py> p.speak()
Polly wants a cracker!
py> p.speak = KillBot().speak
py> p.speak()
Crush! Kill! Destroy!


=== Dynamic class creation ===

Forget about using type(), there's an easier way.


def factory(name, parent_class):
   class MyClass(parent_class):
       def method(self):
           print "Called method"
           return 42
    MyClass.__name__ = name
    return MyClass


Much easier than the equivalent using type.


def method(self):
    print "Called method"
    return 42

type(name, (parent_class,), {'method': method})



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#26469

From"Steven W. Orr" <steveo@syslang.net>
Date2012-08-03 23:14 -0400
Message-ID<mailman.2923.1344050059.4697.python-list@python.org>
In reply to#26455
On 8/3/2012 4:48 PM, Tobiah wrote:
> I have a bunch of classes from another library (the html helpers
> from web2py). There are certain methods that I'd like to add to
> every one of them. So I'd like to put those methods in a class,
> and pass the parent at the time of instantiation. Web2py has
> a FORM class for instance. I'd like to go:
>
> my_element = html_factory(FORM)
>
> Then my_element would be an instance of my class, and also
> a child of FORM.
>
> I started messing with decorators, but it became difficult
> for me to visualise how to do this.
>
> Thanks!
>
> Toby

Your class inherits from whatever is in the class statement.

class Foo(object):
     pass

Here, Foo inherits from object, but you can replace object with any tuple of 
classes which can be redefined before instantiation.

class Base1(object):
     pass

class Base2(object):
     pass

Now we can define Foo2 to inherit from something that better be a tuple of 
classes at instantiation time.

class Foo2(bases):
     pass

bases = (Base1,)

foo2 = Foo2() # foo2 is a Foo2 which inherits from Base1.

bases = (Base1, Bace2)

foob1b2 = Foo2() # foob1b2 is a Foo2 which inherits from Base1 and Base2.

Who was it who said: "Give a man a shovel and he'll dig himself one helluva hole"?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net

[toc] | [prev] | [next] | [standalone]


#26674

Fromalex23 <wuwei23@gmail.com>
Date2012-08-06 19:53 -0700
Message-ID<41f5bfb2-852c-4748-af09-445958471bbd@sn4g2000pbc.googlegroups.com>
In reply to#26455
On Aug 4, 6:48 am, Tobiah <t...@tobiah.org> wrote:
> I have a bunch of classes from another library (the html helpers
> from web2py).  There are certain methods that I'd like to add to
> every one of them.  So I'd like to put those methods in a class,
> and pass the parent at the time of instantiation.  Web2py has
> a FORM class for instance.  I'd like to go:
>
>         my_element = html_factory(FORM)
>
> Then my_element would be an instance of my class, and also
> a child of FORM.

I've lately begun to prefer composition over inheritance for
situations like this:

    class MyElementFormAdapter(object):
        def __init__(self, form):
            self.form = form

        def render_form(self):
            self.form.render()

    my_element = MyElementFormAdapter(FORM)
    my_element.render_form()
    my_element.form.method_on_form()

Advantages include being more simple and obvious than multiple
inheritance, and avoiding namespace clashes:

    class A(object):
        def foo(self):
            print 'a'

    class B(object):
        def foo(self):
            print 'b'

    class InheritFromAB(A, B):
        pass

    class AdaptAB(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b

    >>> inherit = InheritFromAB()
    >>> inherit.foo()
    a
    >>> adapt = AdaptAB(A(), B())
    >>> adapt.a.foo()
    a
    >>> adapt.b.foo()
    b

[toc] | [prev] | [next] | [standalone]


#26735

FromTobiah <toby@tobiah.org>
Date2012-08-07 10:52 -0700
Message-ID<DBcUr.48046$7y4.15211@newsfe23.iad>
In reply to#26674
Interesting stuff.  Thanks.

On 08/06/2012 07:53 PM, alex23 wrote:
> On Aug 4, 6:48 am, Tobiah<t...@tobiah.org>  wrote:
>> I have a bunch of classes from another library (the html helpers
>> from web2py).  There are certain methods that I'd like to add to
>> every one of them.  So I'd like to put those methods in a class,
>> and pass the parent at the time of instantiation.  Web2py has
>> a FORM class for instance.  I'd like to go:
>>
>>          my_element = html_factory(FORM)
>>
>> Then my_element would be an instance of my class, and also
>> a child of FORM.
>
> I've lately begun to prefer composition over inheritance for
> situations like this:
>
>      class MyElementFormAdapter(object):
>          def __init__(self, form):
>              self.form = form
>
>          def render_form(self):
>              self.form.render()
>
>      my_element = MyElementFormAdapter(FORM)
>      my_element.render_form()
>      my_element.form.method_on_form()
>
> Advantages include being more simple and obvious than multiple
> inheritance, and avoiding namespace clashes:
>
>      class A(object):
>          def foo(self):
>              print 'a'
>
>      class B(object):
>          def foo(self):
>              print 'b'
>
>      class InheritFromAB(A, B):
>          pass
>
>      class AdaptAB(object):
>          def __init__(self, a, b):
>              self.a = a
>              self.b = b
>
>      >>>  inherit = InheritFromAB()
>      >>>  inherit.foo()
>      a
>      >>>  adapt = AdaptAB(A(), B())
>      >>>  adapt.a.foo()
>      a
>      >>>  adapt.b.foo()
>      b

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web