❔ Interview Question
What is the difference between
tags: #interview #python #magicmethods #classes
➡️ @DataScienceQ 🤎
What is the difference between
__str__ and __repr__ methods in Python classes, and when would you implementstr__str__ returns a human-readable string representation of an object (e.g., via print(obj)), making it user-friendly for displayrepr__repr__ aims for a more detailed, unambiguous string that's ideally executable as code (like repr(obj)), useful for debugging—imstr __str__ for end-user outrepr__repr__ for developer tools or str __str__ is defined.tags: #interview #python #magicmethods #classes
Please open Telegram to view this post
VIEW IN TELEGRAM
In Python, abstract base classes (ABCs) in the
#python #OOP #classes #abc #inheritance
👉 @DataScience4
abc module define interfaces for subclasses to implement, enforcing polymorphism and preventing instantiation of incomplete classes. Use them for designing robust class hierarchies where specific methods must be overridden.from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
# rect = Rectangle(5, 3)
# print(rect.area()) # 15
# Shape() # Error: Can't instantiate abstract class
#python #OOP #classes #abc #inheritance
👉 @DataScience4
❤3
In Python, Object-Oriented Programming (OOP) allows you to define classes and create objects with attributes and methods. Classes are blueprints for creating objects, and they support key concepts like inheritance, encapsulation, polymorphism, and abstraction.
#Python #OOP #Classes #Inheritance #Polymorphism #Encapsulation #Programming #ObjectOriented #PythonTips #CodeExamples
By: @DataScienceQ🚀
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# Creating instances
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Output: Buddy says Woof!
print(cat.speak()) # Output: Whiskers says Meow!
#Python #OOP #Classes #Inheritance #Polymorphism #Encapsulation #Programming #ObjectOriented #PythonTips #CodeExamples
By: @DataScienceQ
Please open Telegram to view this post
VIEW IN TELEGRAM
👍1🔥1
In Python, "Magic Methods" (also known as Dunder methods, short for "double underscore") are special methods that allow you to define how objects of your class behave with built-in functions and operators. While
Output:
#Python #MagicMethods #DunderMethods #OOP #Classes #PythonTips #CodeExamples #StringRepresentation #ObjectOrientation #Programming
---
By: @DataScienceQ ✨
init handles object initialization, str and repr are crucial for defining an object's string representation.str: Returns a "user-friendly" string representation of an object, primarily for human readability (e.g., when print() is called).repr: Returns an "official" string representation of an object, primarily for developers, often aiming to be unambiguous and allow recreation of the object.class Book:
def init(self, title, author, year):
self.title = title
self.author = author
self.year = year
def str(self):
return f'"{self.title}" by {self.author} ({self.year})'
def repr(self):
return f"Book('{self.title}', '{self.author}', {self.year})"
Creating an instance
my_book = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979)
str is used by print()
print(my_book)
repr is used by the interpreter or explicitly with repr()
print(repr(my_book))
In collections, repr is used by default
bookshelf = [my_book, Book("Pride and Prejudice", "Jane Austen", 1813)]
print(bookshelf)
Output:
"The Hitchhiker's Guide to the Galaxy" by Douglas Adams (1979)
Book('The Hitchhiker\'s Guide to the Galaxy', 'Douglas Adams', 1979)
[Book('The Hitchhiker\'s Guide to the Galaxy', 'Douglas Adams', 1979), Book('Pride and Prejudice', 'Jane Austen', 1813)]
#Python #MagicMethods #DunderMethods #OOP #Classes #PythonTips #CodeExamples #StringRepresentation #ObjectOrientation #Programming
---
By: @DataScienceQ ✨
Python Tip: Mastering
When defining a class in Python,
The
In the
Let's create some cars:
Output:
#PythonTip #OOP #Classes #InitMethod #SelfKeyword #ObjectOriented #PythonProgramming
---
By: @DataScienceQ ✨
init and self in OOP! 🐍When defining a class in Python,
init is a special method (often called the constructor) that gets called automatically every time a new object (instance) of the class is created. It's used to set up the initial state or attributes of that object.The
self parameter is a convention and the first parameter of any instance method. It always refers to the instance of the class itself, allowing you to access its attributes and other methods from within the class.class Car:
def init(self, make, model, year):
self.make = make # Assign 'make' to the instance's 'make' attribute
self.model = model # Assign 'model' to the instance's 'model' attribute
self.year = year # Assign 'year' to the instance's 'year' attribute
def get_description(self):
return f"This is a {self.year} {self.make} {self.model}."
In the
init method, self.make = make means "take the value passed in as make and assign it to the make attribute of this specific Car object."Let's create some cars:
my_car = Car("Toyota", "Camry", 2020)
your_car = Car("Honda", "Civic", 2022)
print(my_car.get_description())
print(your_car.get_description())Output:
This is a 2020 Toyota Camry.
This is a 2022 Honda Civic.
init ensures each object starts with its own data, and self connects you to that data!#PythonTip #OOP #Classes #InitMethod #SelfKeyword #ObjectOriented #PythonProgramming
---
By: @DataScienceQ ✨
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers;
numbers.push_back(5);
numbers.push_back(10);
std::cout << "Vector size: " << numbers.size();
return 0;
}
Vector size: 2
#34.
.size()Member function that returns the number of elements in a container like
std::vector or std::string.#include <iostream>
#include <vector>
int main() {
std::vector<std::string> fruits = {"Apple", "Banana"};
std::cout << "There are " << fruits.size() << " fruits.";
return 0;
}
There are 2 fruits.
#35.
.length()A member function of
std::string that returns its length. It's synonymous with .size().#include <iostream>
#include <string>
int main() {
std::string text = "C++";
std::cout << "The length of the string is: " << text.length();
return 0;
}
The length of the string is: 3
---
#CPP #STL #Algorithms
#36.
#include <algorithm>Includes the standard library algorithms, like sort, find, copy, etc.
#include <iostream>
#include <vector>
#include <algorithm> // Required for std::sort
int main() {
std::vector<int> nums = {3, 1, 4};
std::sort(nums.begin(), nums.end());
std::cout << "Sorting is possible with <algorithm>.";
return 0;
}
Sorting is possible with <algorithm>.
#37.
std::sort()Sorts the elements in a range (e.g., a vector).
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {50, 20, 40, 10, 30};
std::sort(nums.begin(), nums.end());
for(int n : nums) {
std::cout << n << " ";
}
return 0;
}
10 20 30 40 50
#38.
.begin()Returns an iterator pointing to the first element in a container.
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {100, 200, 300};
auto it = nums.begin();
std::cout << "First element: " << *it;
return 0;
}
First element: 100
#39.
.end()Returns an iterator referring to the past-the-end element in the container.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 2, 3};
// .end() points after the last element, used as a boundary
std::cout << "Vector has elements until the end.";
return 0;
}
Vector has elements until the end.
#40.
#defineA preprocessor directive used to create macros or symbolic constants.
#include <iostream>
#define PI 3.14159
int main() {
std::cout << "The value of PI is " << PI;
return 0;
}
The value of PI is 3.14159
---
#CPP #OOP #Classes
#41.
classA keyword used to declare a class, which is a blueprint for creating objects.
#include <iostream>
class Dog {
public:
void bark() {
std::cout << "Woof!";
}
};
int main() {
Dog myDog;
myDog.bark();
return 0;
}
Woof!
#42.
structSimilar to a class, but its members are public by default.