mama
mama

Reputation: 2227

an object with methods in one line

I know it is probably totally useless but...

I was wondering if it is possible to create an object with type() in one line possibly with use of a lambda function.

I want to make a function that increments the value of the object:

I am trying following:

class thing:
    def __init__(self):
        self.val = 0
    def inc(self):
        self.val += 1
obj = thing()

So i just add a lambda function to the dict and a () to the tail of the type:

obj = type('thing', (), {'value':0, 'inc': lambda self: self.value+1})()

The problem here is that the lambda only returns a value, and I don't think I can affect the value of obj

So my question is this: Can i make a lambda function in a type definition that changes the instance value of the object?

Upvotes: 1

Views: 65

Answers (1)

alani
alani

Reputation: 13079

You can use setattr.

>>> obj = type('thing',(),{'value':0, 'inc': lambda self: setattr(self, 'value', self.value+1)})()
>>> obj.inc()
>>> obj.inc()
>>> obj.value
2

But I would agree that it is totally useless.

Upvotes: 3

Related Questions