简体   繁体   中英

Calling a method from a class in Python

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

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

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

PS - You don't pass self as an argument and you have to change the return statement to self.i .

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()

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM