pythonwindowspython-3.8

How do I change a property in a Python function to be optional?


**I want to make a module. The modules can easy to use Python. But I'm in trouble. The code is:

class EasyPy:

    def easy_print(self, condition, implementation):
        if implementation is None:
            implementation = False
            print(condition)
        if condition:
            a = implementation

I invoke this class:

b=EasyPy()
b.easy_print(1)

BUT IT REPORTED AN ERROR:

Traceback (most recent call last):
    File "I:\PycharmProjects\easypy\easypy.py", line 12, in <module>
       b.eprint(1)
TypeError: eprint() missing 1 required positional argument: 'implementation'

I changed the program

class EasyPy:

    def easy_print(self, condition, implementation):
    try:
        if condition:
            a = implementation
    except:
        if implementation is None:
            implementation = False
            print(condition)

But it still reported an error

Traceback (most recent call last):
    File "I:\PycharmProjects\easypy\easypy.py", line 12, in <module>
       b.easy_print(1)
TypeError: easy_print() missing 1 required positional argument: 'implementation'

Mine laptap is Windows 11. Python version is 3.8.10.PLEASE HELP ME!!!


Solution

  • You simply need to give the implementation parameter a default value, like this:

    class EasyPy:
        def easy_print(self, condition, implementation=None):
            if implementation is None:
                implementation = False
            if condition:
                print(implementation)
    

    sample output:

    b = EasyPy()
    b.easy_print(1)
    # Output: False
    
    b.easy_print(1, "Hello!")
    # Output: Hello!
    

    Explanation: