Why does this cord work well?

Asked 2 years ago, Updated 2 years ago, 45 views

I understand that self.n is defined as an instance variable in the code below, but please tell me why this code works well when other.n is not defined.
I'm a beginner, but I look forward to working with you.

class AlwaysPositive:
    def__init__(self, number):
        self.n = number

    def__add__(self, other):
        returnabs(self.n+)
               other.n)

x = AlwaysPositive (-20)
y = AlwaysPositive(10)

print(x+y)

python python3

2022-09-30 21:37

2 Answers

 x = AlwaysPositive (-20)

Do you know that this description calls the _init__ method of the AlwaysPositive class and sets x.n with -20?
Similarly

y=AlwaysPositive(10)

This statement sets y.n to 10.

x+y

This statement invokes the _add__ method of the AlwaysPositive type because x is of the AlwaysPositive type.

The question is what constraints are imposed on the x and y types, and you may think that y(other) should also be AlwaysPositive, but it actually works if you have y.n.

class HasN():
    def__init__(self, n):
        self.n = n 
y = HasN(15)
Returns print(x+y)#=>5

On the other hand, if you try to run x+y for a value that does not have y.n, such as y=15, it returns a runtime error.

Dynamic typing languages, such as python, do not require strong type constraints on other, but have the flexibility to access the other if it has the attribute n, and to generate runtime errors if it becomes uncalculated.The nature of any type as long as other has other.n is sometimes referred to as duck typing.


2022-09-30 21:37

Naoki Fujita's Answer was a little bit more chewed up.

class AlwaysPositive:
    def__init__(self, number):
        self.n = number

    def__add__(self, other):
        returnabs(self.n+)
               other.n)

Create a class called AlwaysPositive

 x = AlwaysPositive (-20)

The AlwaysPositive class _init__ was called to define x which is x.n=-20.

y=AlwaysPositive(10)

Similarly, y is defined as y.n=10 and

print(x+y)

x+y results are displayed.
The __add__ of the AlwaysPositive class is called to calculate x+y.
In other words, __add__(x,y) runs, so

returnabs(x.n+
           y.n)

will be returned.
So in this case other.n is well defined.


2022-09-30 21:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.