সমাধান করা হয়েছে: Python __sub__ ম্যাজিক পদ্ধতি

পাইথনে __sub__ ম্যাজিক পদ্ধতিটি একটি ফাংশনকে কল করতে ব্যবহৃত হয় যা দুটি আর্গুমেন্ট নেয়, কিন্তু প্রথম আর্গুমেন্টটিকে দ্বিতীয় আর্গুমেন্টের ক্লাসের একটি সাবক্লাস হিসাবে ব্যাখ্যা করা হয়। এটি অপ্রত্যাশিত আচরণের দিকে নিয়ে যেতে পারে যদি সাবক্লাসটি __sub__ ম্যাজিক পদ্ধতি বাস্তবায়ন না করে।

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)

ম্যাজিক পদ্ধতি কি

পাইথনে, ম্যাজিক মেথড হল একটি বিশেষ ধরনের ফাংশন যা আপনাকে কোনো ফাংশনের নাম উল্লেখ না করেই কল করতে দেয়। এটি একটি ampersand (&) দিয়ে ফাংশনের নামের উপসর্গ দিয়ে করা হয়।

ম্যাজিক পদ্ধতির তালিকা

পাইথনে যাদু করার বিভিন্ন উপায় রয়েছে। এখানে কয়েকটি আছে:

1. এলোমেলো আমদানি
2. আমদানি সময়
3. গণিত আমদানি sqrt, pi থেকে
4. তারিখ থেকে আমদানি তারিখ, সময়
5. অপারেটর আমদানি থেকে যোগ, বিয়োগ, গুণ, ভাগ
6. functools থেকে আংশিক আমদানি
7. সংগ্রহ থেকে আমদানি ডিক

সম্পর্কিত পোস্ট:

মতামত দিন