Python Data Science Jobs & Interviews
18.6K subscribers
150 photos
3 videos
17 files
263 links
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
Download Telegram
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
👍31
Python Data Science Jobs & Interviews
Question 62: #python
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
👍5🔥1
Python Data Science Jobs & Interviews
Question 64: #python 
What is the purpose of the 'property' decorator in Python? 
 
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👍1
Python Data Science Jobs & Interviews
Question 65: #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
👍1🥰1
Python Data Science Jobs & Interviews
Question 66: #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
Python Data Science Jobs & Interviews
Question 67: #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
2👍2
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
Python Data Science Jobs & Interviews
Question 68: #python
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
1
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
👍2