Reputation: 5432
I know I'm just missing something simple here. I looked through other answers but couldn't find this problem.
>>> class Ben:
... """Can access variable but not method"""
... i = 320894
... def foo(self):
... return i
...
>>> Ben.i
320894
>>> Ben.foo(self)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'self' is not defined
Upvotes: 0
Views: 148
Reputation: 104102
Here are the various way I can think of (off the top 'o my head) to get a class attribute from an instance method:
class Ben:
i = 320894
def foo(self):
return self.i, self.__class__.i, Ben.i, Ben.__dict__['i'], getattr(Ben,'i')
print Ben().foo()
Prints:
(320894, 320894, 320894, 320894, 320894)
Note the Ben().foo()
vs Ben.foo(self)
-- You need an instance of Ben prior to calling foo
and self
is implicit in the calling of foo
as a method of that instance. If you have Ben().foo()
the instance is created similarly to b=Ben()
and then calling b.foo()
self.i
or Ben.i
is the most straightforward. Keep in mind that these can be different i's. self.i
is an instance attribute and Ben.i
is a class attribute:
class Ben(object):
i = 'class i'
def __init__(self):
self.i='instance i'
def foo(self):
return ('Instance i:',self.i, getattr(self,'i'), self.__dict__['i'],
'Class i:',self.__class__.i, getattr(Ben,'i'), Ben.i, Ben.__dict__['i'])
print Ben().foo()
Prints:
('Instance i:', 'instance i', 'instance i', 'instance i',
'Class i:', 'class i', 'class i', 'class i', 'class i')
Upvotes: 1
Reputation: 213401
You don't pass self
yourself. It is a reference to an instance of the class on which you invoke that method. So, you would need to create an instance of Ben
, and invoke that method on that instance:
ben = Ben()
ben.foo()
And instead of:
return i
you need to use:
return self.i
Upvotes: 4
Reputation: 386352
You first must create an instance of the class. "self" is automatically added as the first parameter, you can't pass it in yourself.
ben = Ben()
ben.foo()
Upvotes: 3
Reputation: 34531
You need to instantiate a class instance in this case and invoke the method from that.
>>> class Ben:
"""Can access variable but not method"""
i = 320894
def foo(self):
return self.i
>>> a = Ben()
>>> a.foo()
320894
P.S - You don't pass self
as an argument and you have to change the return statement to self.i
.
Upvotes: 3