3

I am trying to learn about classes, can someone explain to me why this code is not working. I thought when calling a function from a class, "self" is automatically ommitted, but the interpreter tells me that argument "a" is missing (he thinks self = 10).

#! coding=utf-8
class test:
    def __init__(self):
        "do something here"
    def do(self,a):
        return a**2

d = test.do
print(d(10))
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
throwaway17434
  • 821
  • 3
  • 13
  • 22

5 Answers5

10

Instantiate the class first:

d = test().do
print(d(10))  # prints 100

test.do is an unbound method, test().do is bound. The difference is explained in this thread: Class method differences in Python: bound, unbound and static.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
3

You have to instantiate the class first:

d = test()

then you can call a method:

print(d.do(10))
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
2

if you want to use method statically you have to declare it in python

#! coding=utf-8
class test:
    def __init__(self):
        "do something here"

    @staticmethod
    def do(a):
        return a**2

d = test.do
print(d(10)) #and that's work
Philippe T.
  • 1,182
  • 7
  • 11
0

Since you haven't instantiated the class (a fancy term for created) you can't be assigning methods to any random variable. Like already said, you must create the object first, whilst making sure the method you call is a part of the class you called or connected to the class in some way (such as creating another class and then communicating that class with the current class). So you should first type d=test() followed by d.do(). Also, remember that in your declaration of the method you crated a parameter so what you done was wrong in itself anyway, because when you declared the do function, you should have put within the brackets the number you wanted to send to the method to calculate its square. So you type test.do(10) and then the 10 is sent by the self reference to the method to be done whatever it is you told it to do.

One more thing: although it isn't a huge deal, it helps if all of your class names begin with a capital letter, as this is usually the 'pythonic' way to do things, and it also makes your code much easier to read, because when you first called the class, somebody could easily mistaken it for an ordinary function

0
class test:
    def __init__(self):
        "do something here"
    def do(self,a):
        return a**2
    def __call__(self,a):
        return self.do(a)

a = test
test.do(a,10)
#or
a = test().do
a(10)
#or
a = test()
test.do(a,10)
#or
a = test()
print(a(10))
user3252197
  • 79
  • 1
  • 3