I want to put None=0 in Python.

Asked 1 years ago, Updated 1 years ago, 237 views

I only want to place None numerically as 0 such as 1+None=1. What should I do?If 1+None=1 is established even if it cannot be placed as 0.

python

2022-11-07 23:16

3 Answers

Is it like this?

def Add(x,y):
    return(x if x else0)+(y if y else0)


print(Add(10,1))#11
print(Add(10, None))#10
print(Add(None,1))#1
print(Add(None, None))#0


2022-11-08 00:35

Python should not be able to do it.

    The
  • + operator runs __add__ on the left or _radd__ on the right
  • For
  • 1+None, both sides are int and NoneType
  • These types (classes) are built-in and cannot be changed to _add__
  • etc.
  • Therefore, you cannot change the behavior of + in this expression

Once you have your own type, you can change the behavior of + for that type.

Example:

class N(int):

    def__add__(self, other):
        if other==None:
            other = 0
        return N(super().__add__(other))

    def__radd__(self, other):
        return self.__add__(other)

n0 = N(0)
n1 = N(1)
n2 = N(2)

print(f"{n1+None=}")#1
print(f"{None+n1=}")#1
print(f"{n1+2=}")#3
print(f"{1+n2=}")#3
print(f"{n1+n2=}")#3
print(f"{n0+1+None=}")#1

If you want to complete it properly, you need to define other methods to emulate the numeric type.SymPy and others are such approaches.


2022-11-08 07:07

There is no way to avoid the unsupported operand type(s) for +: 'int' and 'NoneType' exception when using the + operator for None, and it will require some redundancy like the other answers.
By the way, there is also a way to get 0 using the or operator, such as None or 0.

x,y=1,None
Returns print((x or 0)+(y or 0))#1


2022-11-08 08:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.