Forwarded from Data Science Premium (Books & Courses)
PayPal - Payeer - Crypto - udst
MasterCard - Credit Card
To request a subscription:
t.iss.one/Hussein_Sheikho
Please open Telegram to view this post
VIEW IN TELEGRAM
Telegram
Eng. Hussein Sheikho
Away
❤1👍1
Python Data Science Jobs & Interviews
❔ Question 60: #python
What is the purpose of the 'str' method in Python classes?
What is the purpose of the 'str' method in Python classes?
class Point:
def init(self, x, y):
self.x = x
self.y = y
def str(self):
return f"Point({self.x}, {self.y})"
# Creating an instance of the Point class
p = Point(3, 4)
# Printing the instance as a string
print(str(p)) # Output: Point(3, 4)
https://t.iss.one/DataScienceQ
👍3🔥2
Python Data Science Jobs & Interviews
class Point: def init(self, x, y): self.x = x self.y = y def str(self): return f"Point({self.x}, {self.y})" # Creating an instance of the Point class p = Point(3, 4) # Printing the instance as a string print(str(p)) …
❤️ The str method in Python classes is a special method used to define the behavior of the class when it is converted to a string representation.
1⃣ The Point class has a str method that is used to return a string representation of an instance.
2⃣ When we call print(str(p)), the str method of the instance p is invoked, and the desired string representation (here "Point(3, 4)") is returned.
✅The str method allows customizing the string representation of class instances, which is useful when you want a readable and meaningful representation of an object.
https://t.iss.one/DataScienceQ
1⃣ The Point class has a str method that is used to return a string representation of an instance.
2⃣ When we call print(str(p)), the str method of the instance p is invoked, and the desired string representation (here "Point(3, 4)") is returned.
✅The str method allows customizing the string representation of class instances, which is useful when you want a readable and meaningful representation of an object.
https://t.iss.one/DataScienceQ
Telegram
Python Data Science Jobs & Interviews
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.
Admin: @Hussein_Sheikho
Admin: @Hussein_Sheikho
👍3❤1
❔ Question 62: #python
What is the purpose of the 'len' method in Python classes?
What is the purpose of the 'len' method in Python classes?
Anonymous Quiz
6%
It is used to initialize the object's state or attributes when an instance is created.
5%
It is used to define the behavior of the class when it is converted to a string representation.
87%
It is used to return the length of the object when the len() function is called on it.
2%
to define a method that can be accessed directly from the class itself, rather than its instances.
👍4🔥2
Python Data Science Jobs & Interviews
❔ Question 62: #python
What is the purpose of the 'len' method in Python classes?
What is the purpose of the 'len' method in Python classes?
class Team:
def init(self, members):
self.members = members
def len(self):
return len(self.members)
# Creating an instance of the Team class
team = Team(['Alice', 'Bob', 'Charlie', 'David'])
# Using the len() function on the instance
print(len(team)) # Output: 4
👍3👏1
Python Data Science Jobs & Interviews
class Team: def init(self, members): self.members = members def len(self): return len(self.members) # Creating an instance of the Team class team = Team(['Alice', 'Bob', 'Charlie', 'David']) # Using the len() function on the…
❤️The 'len' method in Python classes is a special method used to return the length of the object when the len() function is called on it. It allows customizing the behavior of determining the length of objects of the class.
1⃣ The Team class has a len method that returns the length of the members list attribute.
2⃣ When we call len(team), Python internally calls the len method of the team instance, which calculates and returns the length of the members list.
3⃣ Therefore, print(len(team)) outputs 4, as there are four members in the team.
✅The len method allows you to define how the length of objects of your class should be determined, providing flexibility and customization.
https://t.iss.one/DataScienceQ
1⃣ The Team class has a len method that returns the length of the members list attribute.
2⃣ When we call len(team), Python internally calls the len method of the team instance, which calculates and returns the length of the members list.
3⃣ Therefore, print(len(team)) outputs 4, as there are four members in the team.
✅The len method allows you to define how the length of objects of your class should be determined, providing flexibility and customization.
https://t.iss.one/DataScienceQ
Telegram
Python Data Science Jobs & Interviews
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.
Admin: @Hussein_Sheikho
Admin: @Hussein_Sheikho
👍5🔥1
Python Data Science Jobs & Interviews
class Circle:
def init(self, radius):
self._radius = radius
@property
def radius(self):
"""Getter method for radius."""
return self._radius
@radius.setter
def radius(self, value):
"""Setter method for radius."""
if value <= 0:
raise ValueError("Radius must be positive")
self._radius = value
@property
def area(self):
"""Compute the area of the circle."""
return 3.14 * self._radius * self._radius
# Creating an instance of the Circle class
circle = Circle(5)
# Accessing the radius attribute using the property
print(circle.radius) # Output: 5
# Setting a new radius using the property
circle.radius = 7
print(circle.radius) # Output: 7
# Trying to set an invalid radius (should raise an error)
circle.radius = -2 # Raises ValueError: Radius must be positive
# Accessing the area attribute using the property
print(circle.area) # Output: 153.86
Python Data Science Jobs & Interviews
class Circle: def init(self, radius): self._radius = radius @property def radius(self): """Getter method for radius.""" return self._radius @radius.setter def radius(self, value): """Setter method…
❤️The 'property' decorator in Python is used to create a read-only attribute that can be accessed like a regular attribute but has custom getter and setter methods. It allows for controlled access and manipulation of attributes, providing validation or computation logic when getting or setting the attribute value.
1⃣The Circle class uses the @property decorator to define a radius property with custom getter and setter methods.
2⃣The radius property allows controlled access to the _radius attribute, ensuring that only valid radius values are set.
3⃣ The area property computes and returns the area of the circle based on the current radius.
✅By using properties, we ensure that the attributes of the class are accessed and modified through controlled interfaces, encapsulating validation and computation logic within the class.
https://t.iss.one/DataScienceQ
1⃣The Circle class uses the @property decorator to define a radius property with custom getter and setter methods.
2⃣The radius property allows controlled access to the _radius attribute, ensuring that only valid radius values are set.
3⃣ The area property computes and returns the area of the circle based on the current radius.
✅By using properties, we ensure that the attributes of the class are accessed and modified through controlled interfaces, encapsulating validation and computation logic within the class.
https://t.iss.one/DataScienceQ
Telegram
Python Data Science Jobs & Interviews
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.
Admin: @Hussein_Sheikho
Admin: @Hussein_Sheikho
❤1👍1
❔ Question 65: #python
What is the purpose of the 'abstractmethod' decorator in Python?
What is the purpose of the 'abstractmethod' decorator in Python?
Anonymous Quiz
24%
It is used to define a method that can only be accessed by the class itself, not its instances.
53%
It is used to mark a method as abstract, meaning it must be implemented by subclasses.
16%
create a read-only attribute that can be accessed like a regular attribute but has custom getter.
7%
It is used to define a method that is automatically inherited by subclasses.
👍2🥰1🤔1
Python Data Science Jobs & Interviews
❔ Question 65: #python
What is the purpose of the 'abstractmethod' decorator in Python?
What is the purpose of the 'abstractmethod' decorator in Python?
from abc import ABC, abstractmethod
# Define an abstract base class using ABC
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
# Concrete subclass Circle inheriting from Shape
class Circle(Shape):
def init(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
def perimeter(self):
return 2 * 3.14 * self.radius
# Concrete subclass Rectangle inheriting from Shape
class Rectangle(Shape):
def init(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
# Attempting to instantiate Shape directly will raise TypeError
try:
s = Shape()
except TypeError as e:
print(f"TypeError: {e}")
# Instantiate Circle and Rectangle objects
circle = Circle(5)
rectangle = Rectangle(4, 6)
# Calculate and print area and perimeter of Circle and Rectangle
print(f"Circle - Area: {circle.area()}, Perimeter: {circle.perimeter()}")
print(f"Rectangle - Area: {rectangle.area()}, Perimeter: {rectangle.perimeter()}")
👏1
Python Data Science Jobs & Interviews
from abc import ABC, abstractmethod # Define an abstract base class using ABC class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass # Concrete subclass Circle inheriting from…
1⃣The Shape class is defined as an abstract base class using ABC from the abc module.
2⃣area and perimeter methods in Shape are marked as abstract using @abstractmethod, which means any subclass of Shape must implement these methods.
3⃣ Circle and Rectangle are concrete subclasses of Shape that provide implementations for area and perimeter.
4⃣ Attempting to instantiate Shape directly raises a TypeError because abstract classes cannot be instantiated.
5⃣ Circle and Rectangle demonstrate how abstract methods enforce a contract that subclasses must follow, ensuring consistent behavior across different shapes.
✅The abstractmethod decorator in Python is used to mark a method as abstract, meaning it must be implemented by subclasses. Classes containing abstract methods cannot be instantiated directly; they serve as blueprints for subclasses to provide concrete implementations of the abstract.
https://t.iss.one/DataScienceQ
2⃣area and perimeter methods in Shape are marked as abstract using @abstractmethod, which means any subclass of Shape must implement these methods.
3⃣ Circle and Rectangle are concrete subclasses of Shape that provide implementations for area and perimeter.
4⃣ Attempting to instantiate Shape directly raises a TypeError because abstract classes cannot be instantiated.
5⃣ Circle and Rectangle demonstrate how abstract methods enforce a contract that subclasses must follow, ensuring consistent behavior across different shapes.
✅The abstractmethod decorator in Python is used to mark a method as abstract, meaning it must be implemented by subclasses. Classes containing abstract methods cannot be instantiated directly; they serve as blueprints for subclasses to provide concrete implementations of the abstract.
https://t.iss.one/DataScienceQ
Telegram
Python Data Science Jobs & Interviews
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.
Admin: @Hussein_Sheikho
Admin: @Hussein_Sheikho
👍1🥰1
❔ Question 66: #python
What is the purpose of the 'getattr' function in Python?
What is the purpose of the 'getattr' function in Python?
Anonymous Quiz
16%
It is used to set the value of an attribute on an object dynamically.
12%
It is used to delete an attribute from an object.
64%
It is used to get the value of an attribute from an object.
8%
It is used to check if a specific attribute exists within a class.
👍2🥰2
Python Data Science Jobs & Interviews
❔ Question 66: #python
What is the purpose of the 'getattr' function in Python?
What is the purpose of the 'getattr' function in Python?
class Person:
def init(self, name, age):
self.name = name
self.age = age
# Create an instance of the Person class
person = Person('Alice', 30)
# Using getattr to dynamically retrieve attributes
name = getattr(person, 'name')
age = getattr(person, 'age')
city = getattr(person, 'city', 'Unknown') # Providing a default value if attribute doesn't exist
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
https://t.iss.one/DataScienceQ
👍1
Python Data Science Jobs & Interviews
class Person: def init(self, name, age): self.name = name self.age = age # Create an instance of the Person class person = Person('Alice', 30) # Using getattr to dynamically retrieve attributes name = getattr(person, 'name') age = getattr(person…
1⃣We define a Person class with attributes name and age.
2⃣An instance person of the Person class is created.
3⃣We use getattr to dynamically retrieve the values of name and age attributes from the person object.
4⃣ The third usage of getattr attempts to retrieve the city attribute, which does not exist in the Person class, so it defaults to 'Unknown'.
✅This demonstrates how getattr can be used to fetch attribute values from objects dynamically, handling cases where attributes may or may not exist.
https://t.iss.one/DataScienceQ
2⃣An instance person of the Person class is created.
3⃣We use getattr to dynamically retrieve the values of name and age attributes from the person object.
4⃣ The third usage of getattr attempts to retrieve the city attribute, which does not exist in the Person class, so it defaults to 'Unknown'.
✅This demonstrates how getattr can be used to fetch attribute values from objects dynamically, handling cases where attributes may or may not exist.
https://t.iss.one/DataScienceQ
Telegram
Python Data Science Jobs & Interviews
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.
Admin: @Hussein_Sheikho
Admin: @Hussein_Sheikho
❔ Question 67: #python
What is the purpose of the 'sys.argv' list in Python?
What is the purpose of the 'sys.argv' list in Python?
Anonymous Quiz
59%
It is used to store command-line arguments passed to a Python script.
15%
It is used to store the paths of imported modules in a Python script.
18%
It is used to store environment variables of the system.
8%
It is used to store the names of built-in functions in Python.
👍2❤1
Python Data Science Jobs & Interviews
❔ Question 67: #python
What is the purpose of the 'sys.argv' list in Python?
What is the purpose of the 'sys.argv' list in Python?
import sys
# Print all command-line arguments
print("All arguments:", sys.argv)
# Print the script name
print("Script name:", sys.argv[0])
# Print the command-line arguments excluding the script name
for i in range(1, len(sys.argv)):
print(f"Argument {i}:", sys.argv[i])
If this script is executed with command-line arguments like:
python script.py arg1 arg2 arg3
The output will be:
All arguments: ['script.py', 'arg1', 'arg2', 'arg3']
Script name: script.py
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3
https://t.iss.one/DataScienceQ
Telegram
Python Data Science Jobs & Interviews
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.
Admin: @Hussein_Sheikho
Admin: @Hussein_Sheikho
❤2👍2
Python Data Science Jobs & Interviews
import sys # Print all command-line arguments print("All arguments:", sys.argv) # Print the script name print("Script name:", sys.argv[0]) # Print the command-line arguments excluding the script name for i in range(1, len(sys.argv)): print(f"Argument…
1⃣ sys.argv[0] returns the script name (script.py).
2⃣The command-line arguments arg1, arg2, and arg3 are stored in the sys.argv list.
3⃣ A for loop is used to print all arguments except the script name.
https://t.iss.one/DataScienceQ
2⃣The command-line arguments arg1, arg2, and arg3 are stored in the sys.argv list.
3⃣ A for loop is used to print all arguments except the script name.
https://t.iss.one/DataScienceQ
Telegram
Python Data Science Jobs & Interviews
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.
Admin: @Hussein_Sheikho
Admin: @Hussein_Sheikho
👍4❤3
In your opinion, in what direction should we continue the questions in the coming week?
Anonymous Poll
35%
Numpy
38%
Pandas
20%
Matplotlib
7%
Other, say in comment
🔥8👍2🥰1
❔ Question 68: #python
What is the purpose of the 'str' method in Python classes?
What is the purpose of the 'str' method in Python classes?
Anonymous Quiz
16%
It is used to initialize the object's state or attributes when an instance is created.
15%
define a method that can be accessed directly from the class itself, rather than its instances.
10%
It is used to check if a specific attribute exists within the class.
60%
It is used to define the behavior of the class when it is converted to a string representation.
🔥12❤2😁1