简体   繁体   中英

How to print a statement everytime when i call function inside class

class Test:
    print("This is class Test")
    def meth1(self):
        print("This is meth1")
    def meth2(self):
        print("This is meth2")

a=Test()
  1. My question is everytime when i call meth1 and meth2 inside class. I need to have statement printed before function print statements say. "This is from class Test"

  2. output should be like:

     This is from class test This is from meth1 This is from class test This is from meth2

You can use the concept of decorators. Just like given below

def desc_message(func):
    def wrapper(*args, **kwargs):
        print("This is class test")
        func(*args, **kwargs)
    return wrapper

class Test:
    @desc_message
    def meth1(self):
        print("This is meth1")
    
    @desc_message
    def meth2(self):
        print("This is meth2")

a=Test()

The output will be

This is class test
This is meth1
This is class test
This is meth2

Didn't understood your question very well but here is the solution with what i've understood:

  • Make a function that contains text which you want to call in other function.
  • Call that function in other functions using self.func_name()
class Test:
    def desc(self):
        print("This is class Test")
    def meth1(self):
        self.desc()
        print("This is meth1")
    def meth2(self):
        self.desc()
        print("This is meth2")

a=Test()
a.meth2()
>> This is class Test
>> This is meth2

You can simply add the print statement to the instance method:

class Test:

def meth1(self):
    print("This is class Test") 
    print("This is meth1") 

def meth2(self): 
    print("This is class Test") 
    print("This is meth2")

a = Test()
a.meth1()
a.meth2()

Output:

This is class Test
This is meth1
This is class Test
This is meth2

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