[Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError
spir
denis.spir at gmail.com
Tue Feb 25 00:52:16 CET 2014
On 02/24/2014 08:19 PM, Sangeeth Saravanaraj wrote:
> Sorry, I should have described what I was trying!
>
> I want to create a decorator which should do the following things:
>
> - When an object of the decorated class is created, the objects name
> (say the value of the incoming "id" argument) should be stored as a record
> in a table in a database.
> - When an object of the decorated class is deleted, the record with this
> deleted objects name (i.e. object.id) should be removed from the table.
>
> You can safely assume that all the database operations are working fine!
>
> Now, for example - consider the following snippet:
>
> @saveme
> class A(object):
> def __init__(self, id):
> self.id = id
>
> @saveme
> class B(object):
> def __init__(self, id):
> self.id = id
>
> "saveme" should do what I have explained earlier.
>
> a1 = A("A1")
> a2 = A("A2")
> a3 = A("A3")
> b1 = B("B1")
> b2 = B("B2")
>
> At this point if I query and print all the records in a table, I should get
> the following:
> output: ["A1", "A2", "A3", "B1", "B2"]
>
> del a1
> del a2
> del a3
> del b1
> del b2
>
> At this point, all entries in the table should be deleted; query should
> return an empty list!
>
> And, I want to highlight that the classes that are being decorated with
> "saveme" can de derived classes too!
>
> What is the best way to do this?!
>
> Thank you,
>
> Sangeeth
Your problem looks like a typical "crosscutting" (transversal) concern addressed
by AOP (Aspect Oriented Programming). Their usual example is in fact logging.
Look at the wikipedia page:
https://en.wikipedia.org/wiki/Aspect-oriented_programming
Not that it would help you solve it _in python_, but this may serve at least to
better understand what kind of problem you are actually facing; and why it is
annoying in programming (with common languages); what may be your options.
[I have no better approach than yours, using magic metamethods, and a decorator
to wrap it all.]
d
More information about the Tutor
mailing list