Yakagadziriswa: Python __sub__ mashiripiti nzira

Iyo __sub__ mashiripiti nzira muPython inoshandiswa kudaidza basa rinotora nharo mbiri, asi nharo yekutanga inodudzirwa sechikamu chechikamu chechipiri chenharo. Izvi zvinogona kutungamirira kumaitiro asingatarisirwi kana subclass ikasashandisa __sub__ mashiripiti nzira.

The __sub__ magic method is used to implement the subtraction operator for objects. It is called when the - operator is used on two objects of the same type. The __sub__ method should return the result of the subtraction operation.

For example, if we have a class that represents a complex number, we could define the __sub__ method like this:

class ComplexNumber: def __init__(self, real, imaginary): self.real = real self.imaginary = imaginary def __sub__(self, other): return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)

Now we can use the - operator on two ComplexNumber objects:

c1 = ComplexNumber(1, 2) c2 = ComplexNumber(3, 4) c3 = c1 - c2 print(c3) # Prints ComplexNumber(real=-2, imaginary=-2)

Chii chinonzi Magic Method

MuPython, mashiripiti nzira imhando yakakosha yebasa iyo inokutendera kuti ufonere basa pasina kudoma zita rayo. Izvi zvinoitwa nekugadzirisa zita rebasa racho neampersand (&).

Rondedzero yeMashiripiti nzira

Kune dzakawanda nzira dzakasiyana dzekuita mashiripiti muPython. Heano mashoma:

1. kupinza zvisina tsarukano
2. kupinza nguva
3. kubva math import sqrt, pi
4. kubva datetime import date, nguva
5. kubva kune opareta pinza wedzera, bvisa, wedzera, patsanura
6. kubva ku functools kupinza chikamu
7. kubva kuunganidzwa pinza deque

Related posts:

Leave a Comment