EricVonB
EricVonB

Reputation: 238

How to use a function inside a class' __init__ function

In Python 2.7 I have this class definition:

class foo:
    def __init__(self,ahg):
        self.ahg=ahg
        def oaf(arg):
            return arg*2
        self.tooAhg=self.oaf(self.ahg)

At console I make the following statements

>>> bibi=foo(1)
>>> vars(bibi)
{'ahg': 1}

I don't know why vars(bibi) does not return {'ahg': 1, 'tooAhg': 2}. Please help! Furthermore, another unsuccessful strategy is this:

class foo:
    def __init__(self,ahg):
        self.ahg=ahg
        self.tooAhg=self.oaf()
    def oaf(self):
        return self.ahg*2

Upvotes: 2

Views: 6758

Answers (2)

Saksham Varma
Saksham Varma

Reputation: 2140

Not sure if this fits your use-case but if tooAhg has to be 2*ahg always, you should use properties:

class Foo(object):
    def __init__(self, ahg):
        self.ahg = ahg

    @property
    def tooAhg(self):
        return 2 * self.ahg

Now, you can access tooAhg like any other class field (ex. self.tooAhg), without worrying about updating it whenever you update ahg

Upvotes: 1

cdarke
cdarke

Reputation: 44434

If you had read the error message from the first example then that might have given you a clue.

self.tooAhg=self.oaf(self.ahg)
AttributeError: foo instance has no attribute 'oaf'

The function name is oaf, not self.oaf.

class foo:
    def __init__(self,ahg):
        self.ahg=ahg
        def oaf(arg):
            return arg*2
        self.tooAhg=oaf(self.ahg)

bibi=foo(1)
print vars(bibi)

Gives:

{'tooAhg': 2, 'ahg': 1}

If you want to make the function oaf an attribute of the object, then:

self.oaf = oaf

Upvotes: 4

Related Questions