Similar Problems
Similar Problems not available
Check If Object Instance Of Class - Leetcode Solution
Companies:
LeetCode: Check If Object Instance Of Class Leetcode Solution
Difficulty: Unknown
Topics: unknown
Problem:
Given a variable 'obj', write a function to check whether 'obj' is an instance of a particular class or not.
Solution:
To solve this problem, we can use the 'isinstance()' function in Python. This function takes in two parameters - the object we want to check and the class we want to check against. It returns True if the object is an instance of the class, and False otherwise.
Here's the Python code to implement this solution:
def check_instance(obj, cls):
return isinstance(obj, cls)
We can then call this function with an object and a class to check if the object is an instance of that class.
Example:
Suppose we have a class called 'Person', with a few attributes and methods:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}.")
We can create an instance of this class:
person1 = Person("Alice", 25)
Now, we can use our function to check if 'person1' is an instance of 'Person':
print(check_instance(person1, Person)) # Output: True
We can also check if another object is an instance of 'Person', even if it wasn't created from that class:
some_obj = "This is not a person object."
print(check_instance(some_obj, Person)) # Output: False
This solution should work with any class and object in Python.
Check If Object Instance Of Class Solution Code
1