Hướng dẫn python call sub function

Python functions are first-class objects. What is first class function in Python

So the first piece of code is perfectly valid. It just adds a property B to the function, which can later be called using A.B().

But for the second piece of code, this is invalid, as self.A returns a reference to A method of class Student

>

self.A does not have an attribute B, so it returns an error

AttributeError: 'method' object has no attribute 'B'

Now a quick fix would be to assign it to self.B

class Student:
    def A(self):
        def B():
            print("I'm B")
        self.B = B

a = Student()
a.A()
a.B()

Although the above code works, it is a very bad way, as you will have to always call A for every object instantiated before calling B.

EDIT2: Thank you all for your help! EDIT: on adding @staticmethod, it works. However I am still wondering why i am getting a type error here.

Nội dung chính

  • Classmethod example
  • Alternative writing
  • classmethod vs staticmethod
  • How do you call a class function?
  • Can I call function in class Python?
  • How do you use the class function in Python?
  • How do I call a function in Python?

I have just started OOPS and am completely new to it. I have a very basic question regarding the different ways I can call a function from a class. I have a testClass.py file with the code:

class MathsOperations:
    def __init__ (self, x, y):
        self.a = x
        self.b = y
    def testAddition (self):
        return (self.a + self.b)

    def testMultiplication (self):
        return (self.a * self.b)

I am calling this class from another file called main.py with the following code:

from testClass import MathsOperations

xyz = MathsOperations(2, 3)
print xyz.testAddition()

This works without any issues. However, I wanted to use the class in a much simpler way.

I have now put the following code in the testClass.py file. I have dropped the init function this time.

class MathsOperations:
    def testAddition (x, y):
        return x + y

    def testMultiplication (a, b):
        return a * b

calling this using;

from testClass import MathsOperations
xyz = MathsOperations()
print xyz.testAddition(2, 3)

this doesn't works. Can someone explain what is happening wrongly in case 2? How do I use this class?

The error i get is "TypeError: testAddition() takes exactly 2 arguments (3 given)"

A class method is a method that’s shared among all objects. To call a class method, put the class as the first argument.

Class methods can be can be called from instances and from the class itself. All of these use the same method. The method can use the classes variables and methods.

Related course: Complete Python Programming Course & Exercises

Example

Classmethod example

To turn a method into a classmethod, add @classmethod before the method definition. As parameter the method always takes the class.

The example below defines a class method. The class method can then be used by the class itself. In this example the class method uses the class property name.

1
2
3
4
5
6
7
8
class Fruit:
name = 'Fruitas'

@classmethod
def printName(cls):
print('The name is:', cls.name)

Fruit.printName()

You can use a classmethod with both objects and the class:

1
2
3
4
5
6
apple = Fruit()
berry = Fruit()

Fruit.printName()
apple.printName()
berry.printName()

The parameter name now belongs to the class, if you’d change the name by using an object it ignores that. But if you’d do that by the class it changes, example below:

1
2
3
4
5
6
7
8
9
apple.name="Apple"
Fruit.printName()
apple.printName()
berry.printName()

Fruit.name="Apple"
Fruit.printName()
apple.printName()
berry.printName()

Alternative writing

Often the pythonic notation is used, but this is not strictly required.
You can also use a classmethod like this:

1
2
3
4
5
6
7
8
class Fruit:
name = 'Fruitas'

def printName(cls):
print('The name is:', cls.name)

Fruit.printAge = classmethod(Fruit.printName)
Fruit.printAge()

classmethod vs staticmethod

Like a static method, a class method doesn’t need an object to be instantiated.

A class method differs from a static method in that a static method doesn’t know about the class itself. In a classmethod, the parameter is always the class itself.

a static method knows nothing about the class or instance. You can just as well use a function call.

a class method gets the class when the method is called. It knows abouts the classes attributes and methods.

If you are a beginner, then I highly recommend this book.

Exercises

Exercises for classmethod article:

  • What is a classmethod?
  • How does a classmethod differ from a staticmethod?

Download examples

How do you call a class function?

To call some function before main() method in C++,.

Create a class..

Create a function in this class to be called..

Create the constructor of this class and call the above method in this constructor..

Now declare an object of this class as a global variable..

Can I call function in class Python?

To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self. distToPoint . self is variable storing the current Coordinates class instance.

How do you use the class function in Python?

A Class is like an object constructor, or a "blueprint" for creating objects..

Create a Class. To create a class, use the keyword class : ... .

Create Object. Now we can use the class named MyClass to create objects: ... .

The self Parameter. ... .

Modify Object Properties. ... .

Delete Object Properties. ... .

Delete Objects..

How do I call a function in Python?

Once we have defined a function, we can call it from another function, program, or even the Python prompt. To call a function we simply type the function name with appropriate parameters. >>> greet('Paul') Hello, Paul.