Built-in Object & Attribute Functions in python

1. type()

Description: Returns the type of an object.

python

# 1. Basic types
print(type(5))              # <class 'int'>
print(type(3.14))           # <class 'float'>
print(type("hello"))        # <class 'str'>
print(type(True))           # <class 'bool'>

# 2. Collection types
print(type([1, 2, 3]))      # <class 'list'>
print(type((1, 2, 3)))      # <class 'tuple'>
print(type({1, 2, 3}))      # <class 'set'>
print(type({"a": 1}))       # <class 'dict'>

# 3. Special types
print(type(None))           # <class 'NoneType'>
print(type(print))          # <class 'builtin_function_or_method'>

2. isinstance()

Description: Checks if object is instance of specified type(s).

python

# 1. Check basic types
print(isinstance(5, int))           # True
print(isinstance(3.14, float))      # True
print(isinstance("hello", str))     # True

# 2. Check multiple types
print(isinstance(5, (int, float)))  # True
print(isinstance(3.14, (int, str))) # False

# 3. Check collection types
print(isinstance([1, 2], list))     # True
print(isinstance((1, 2), tuple))    # True

# 4. Check with None
print(isinstance(None, type(None))) # True

# 5. Check function type
def my_func(): pass
print(isinstance(my_func, type(my_func)))  # True

# 6. Check string or list
print(isinstance("test", (str, list)))     # True

# 7. Check number types
print(isinstance(10, (int, float, complex)))  # True

# 8. Check boolean
print(isinstance(True, bool))       # True

# 9. Check dictionary
print(isinstance({"a": 1}, dict))   # True

# 10. Check set
print(isinstance({1, 2}, set))      # True

3. hasattr()

Description: Checks if object has specified attribute.

python

# 1. Check string methods
s = "hello"
print(hasattr(s, 'upper'))      # True
print(hasattr(s, 'split'))      # True

# 2. Check list methods
lst = [1, 2, 3]
print(hasattr(lst, 'append'))   # True
print(hasattr(lst, 'pop'))      # True

# 3. Check dictionary methods
d = {"a": 1}
print(hasattr(d, 'keys'))       # True
print(hasattr(d, 'values'))     # True

# 4. Check built-in functions
print(hasattr(print, '__name__'))  # True

# 5. Check number attributes
x = 10
print(hasattr(x, 'real'))       # True
print(hasattr(x, 'imag'))       # True

# 6. Check module attributes
import math
print(hasattr(math, 'pi'))      # True

# 7. Check non-existent attributes
print(hasattr("hello", 'nonexistent'))  # False

# 8. Check tuple methods
t = (1, 2, 3)
print(hasattr(t, 'count'))      # True

# 9. Check set methods
s = {1, 2, 3}
print(hasattr(s, 'add'))        # True

# 10. Check function attributes
def func(): pass
print(hasattr(func, '__name__'))  # True

4. getattr()

Description: Gets the value of an attribute.

python

# 1. Get string methods
s = "hello"
upper_method = getattr(s, 'upper')
print(upper_method())           # HELLO

# 2. Get list methods
lst = [1, 2, 3]
append_method = getattr(lst, 'append')
append_method(4)
print(lst)                      # [1, 2, 3, 4]

# 3. Get with default value
d = {"a": 1}
value = getattr(d, 'nonexistent', 'default')
print(value)                    # default

# 4. Get number attributes
x = 5 + 3j
print(getattr(x, 'real'))       # 5.0
print(getattr(x, 'imag'))       # 3.0

# 5. Get built-in constants
import math
print(getattr(math, 'pi'))      # 3.141592653589793

# 6. Get function attributes
def greet(): return "Hello"
print(getattr(greet, '__name__'))  # greet

# 7. Get dictionary methods
d = {"a": 1}
keys_method = getattr(d, 'keys')
print(list(keys_method()))      # ['a']

# 8. Get tuple methods
t = (1, 2, 2, 3)
count_method = getattr(t, 'count')
print(count_method(2))          # 2

# 9. Get module functions
import random
rand_func = getattr(random, 'randint')
print(rand_func(1, 10))         # Random number between 1-10

# 10. Get set methods
my_set = {1, 2, 3}
add_method = getattr(my_set, 'add')
add_method(4)
print(my_set)                   # {1, 2, 3, 4}

5. id()

Description: Returns unique identity (memory address) of object.

python

# 1. IDs of integers
a = 5
b = 5
print(id(a))                    # Same as id(b) due to caching
print(id(a) == id(b))           # True

# 2. IDs of strings
s1 = "hello"
s2 = "hello"
print(id(s1) == id(s2))         # True (string interning)

# 3. IDs of different objects
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
print(id(lst1) == id(lst2))     # False

# 4. ID of None
print(id(None))                 # Always the same

# 5. ID after modification
x = [1, 2]
original_id = id(x)
x.append(3)
print(id(x) == original_id)     # True

# 6. IDs of functions
def func1(): pass
def func2(): pass
print(id(func1) == id(func2))   # False

# 7. ID of built-in functions
print(id(print))                # Unique ID

# 8. IDs of boolean values
print(id(True))                 # Always same
print(id(False))                # Always same

# 9. ID of empty collections
empty_list = []
empty_dict = {}
print(id(empty_list) != id(empty_dict))  # True

# 10. ID comparison with is operator
a = [1, 2]
b = a
print(id(a) == id(b))           # True

6. dir()

Description: Returns list of valid attributes for object.

python

# 1. Dir of string
s = "hello"
print('upper' in dir(s))        # True
print('split' in dir(s))        # True

# 2. Dir of list
lst = [1, 2, 3]
print('append' in dir(lst))     # True
print('pop' in dir(lst))        # True

# 3. Dir of dictionary
d = {"a": 1}
print('keys' in dir(d))         # True
print('values' in dir(d))       # True

# 4. Dir of number
x = 10
print('real' in dir(x))         # True
print('imag' in dir(x))         # True

# 5. Dir of function
def func(): pass
print('__name__' in dir(func))  # True

# 6. Dir of module
import math
math_attrs = dir(math)
print('sqrt' in math_attrs)     # True
print('pi' in math_attrs)       # True

# 7. Dir of None
none_attrs = dir(None)
print('__class__' in none_attrs)  # True

# 8. Dir of boolean
print(dir(True))                # Shows bool attributes

# 9. Dir of tuple
t = (1, 2, 3)
print('count' in dir(t))        # True
print('index' in dir(t))        # True

# 10. Dir without arguments (current scope)
local_vars = dir()
print('__name__' in local_vars)  # True

7. repr()

Description: Returns official string representation of object.

python

# 1. String representation
s = "hello"
print(repr(s))                  # "'hello'"

# 2. Number representation
print(repr(123))                # '123'
print(repr(3.14))               # '3.14'

# 3. List representation
lst = [1, 2, 3]
print(repr(lst))                # '[1, 2, 3]'

# 4. Dictionary representation
d = {"a": 1, "b": 2}
print(repr(d))                  # "{'a': 1, 'b': 2}"

# 5. Tuple representation
t = (1, 2, 3)
print(repr(t))                  # '(1, 2, 3)'

# 6. Set representation
s = {1, 2, 3}
print(repr(s))                  # '{1, 2, 3}'

# 7. None representation
print(repr(None))               # 'None'

# 8. Boolean representation
print(repr(True))               # 'True'
print(repr(False))              # 'False'

# 9. Special characters in strings
s = "hello\nworld"
print(repr(s))                  # "'hello\\nworld'"

# 10. Function representation
def greet(): return "Hello"
print(repr(greet))              # '<function greet at 0x...>'

These functions are essential for introspection, debugging, and understanding objects in Python!

I’ll explain built-in object and attribute functions in Python with 7 simple examples for each:

1. type()

Syntax: type(object) or type(name, bases, dict)
Description: Returns the type of an object or creates a new type.

Examples:

python

# 1. Check type of basic objects
print(type(5))              # <class 'int'>
print(type("hello"))        # <class 'str'>
print(type([1, 2, 3]))      # <class 'list'>

# 2. Check type of variables
x = 3.14
print(type(x))              # <class 'float'>

# 3. Check if object is of specific type
if type(10) == int:
    print("It's an integer")  # This will print

# 4. Create a new class dynamically
MyClass = type('MyClass', (), {'x': 10})
obj = MyClass()
print(obj.x)                # 10

# 5. Check type of functions
def my_func():
    pass
print(type(my_func))        # <class 'function'>

# 6. Check type of None
print(type(None))           # <class 'NoneType'>

# 7. Compare types
print(type(5) is int)       # True

2. isinstance()

Syntax: isinstance(object, classinfo)
Description: Checks if an object is an instance of a class or tuple of classes.

Examples:

python

# 1. Check if object is integer
print(isinstance(5, int))           # True

# 2. Check if object is string or list
print(isinstance("hello", (str, list)))  # True

# 3. Check with custom class
class Dog:
    pass

my_dog = Dog()
print(isinstance(my_dog, Dog))      # True

# 4. Check inheritance
class Animal:
    pass

class Cat(Animal):
    pass

my_cat = Cat()
print(isinstance(my_cat, Animal))   # True (inheritance)

# 5. Check with built-in types
numbers = [1, 2, 3]
print(isinstance(numbers, list))    # True

# 6. Check multiple types
value = 3.14
print(isinstance(value, (int, float)))  # True

# 7. Check with None
print(isinstance(None, type(None))) # True

3. issubclass()

Syntax: issubclass(class, classinfo)
Description: Checks if a class is a subclass of another class.

Examples:

python

# 1. Basic inheritance check
class Animal:
    pass

class Dog(Animal):
    pass

print(issubclass(Dog, Animal))      # True

# 2. Check with built-in types
print(issubclass(bool, int))        # True (bool is subclass of int)

# 3. Multiple inheritance check
class A: pass
class B(A): pass
class C(B): pass

print(issubclass(C, A))             # True

# 4. Check with tuple of classes
print(issubclass(str, (int, str)))  # True

# 5. Class is subclass of itself
print(issubclass(Animal, Animal))   # True

# 6. Check with non-inheritance
class Bird: pass
print(issubclass(Bird, Animal))     # False

# 7. Built-in type hierarchy
print(issubclass(list, object))     # True (all classes inherit from object)

4. id()

Syntax: id(object)
Description: Returns the unique identity (memory address) of an object.

Examples:

python

# 1. Get ID of integers
x = 5
print(id(x))                # e.g., 140735849845792

# 2. Compare IDs of same values
a = 10
b = 10
print(id(a) == id(b))       # True (small integers are cached)

# 3. Different objects have different IDs
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(id(list1) == id(list2))  # False

# 4. ID remains same for same object
x = [1, 2, 3]
y = x
print(id(x) == id(y))       # True

# 5. ID of functions
def my_func():
    pass
print(id(my_func))          # Unique ID

# 6. ID after modification
lst = [1, 2]
id1 = id(lst)
lst.append(3)
id2 = id(lst)
print(id1 == id2)           # True (same object modified)

# 7. ID of None
print(id(None))             # Always same ID

5. hasattr()

Syntax: hasattr(object, name)
Description: Checks if an object has an attribute with the given name.

Examples:

python

# 1. Check for string methods
s = "hello"
print(hasattr(s, 'upper'))      # True

# 2. Check for list methods
lst = [1, 2, 3]
print(hasattr(lst, 'append'))   # True

# 3. Check for non-existent attribute
print(hasattr(s, 'nonexistent')) # False

# 4. Check with custom class
class Person:
    def __init__(self, name):
        self.name = name

p = Person("Alice")
print(hasattr(p, 'name'))       # True

# 5. Check for methods
print(hasattr(p, '__init__'))   # True

# 6. Check with built-in objects
print(hasattr(5, 'real'))       # True

# 7. Check for private attributes
class Test:
    def __init__(self):
        self._private = "secret"

t = Test()
print(hasattr(t, '_private'))   # True

6. getattr()

Syntax: getattr(object, name[, default])
Description: Gets the value of an attribute, with optional default if not found.

Examples:

python

# 1. Get string method
s = "hello"
upper_method = getattr(s, 'upper')
print(upper_method())           # HELLO

# 2. Get attribute with default
class Person:
    def __init__(self, name):
        self.name = name

p = Person("Bob")
age = getattr(p, 'age', 25)     # Default if attribute not found
print(age)                      # 25

# 3. Get built-in attributes
x = 10
print(getattr(x, 'real'))       # 10

# 4. Get method and call it
lst = [1, 2, 3]
append_method = getattr(lst, 'append')
append_method(4)
print(lst)                      # [1, 2, 3, 4]

# 5. Get class attributes
class MyClass:
    class_attr = "class value"

print(getattr(MyClass, 'class_attr'))  # "class value"

# 6. Handle missing attribute
try:
    value = getattr(p, 'nonexistent')
except AttributeError:
    value = "default"
print(value)                    # "default"

# 7. Get special methods
print(getattr([], '__len__'))   # <method-wrapper '__len__' of list object>

7. setattr()

Syntax: setattr(object, name, value)
Description: Sets the value of an attribute, creating it if it doesn’t exist.

Examples:

python

# 1. Set attribute on custom object
class Person:
    pass

p = Person()
setattr(p, 'name', 'Charlie')
print(p.name)                   # Charlie

# 2. Set multiple attributes
attributes = {'age': 30, 'city': 'New York'}
for key, value in attributes.items():
    setattr(p, key, value)
print(p.age, p.city)            # 30 New York

# 3. Modify existing attribute
setattr(p, 'age', 31)
print(p.age)                    # 31

# 4. Set private attribute
setattr(p, '_secret', 'hidden')
print(p._secret)                # hidden

# 5. Set class attribute
setattr(Person, 'species', 'Human')
print(Person.species)           # Human

# 6. Set attribute with dynamic name
attr_name = 'dynamic_attr'
setattr(p, attr_name, 'dynamic value')
print(p.dynamic_attr)           # dynamic value

# 7. Set on built-in types (usually not recommended)
# Note: This may not work for all built-in types
class CustomList(list):
    pass

cl = CustomList([1, 2, 3])
setattr(cl, 'custom_attr', 'test')
print(cl.custom_attr)           # test

These functions are essential for introspection and dynamic attribute handling in Python, enabling powerful meta-programming capabilities.

Similar Posts

  • Generalization vs. Specialization

    Object-Oriented Programming: Generalization vs. Specialization Introduction Inheritance in OOP serves two primary purposes: Let’s explore these concepts with clear examples. 1. Specialization (Extending Functionality) Specialization involves creating a new class that inherits all features from a parent class and then adds new, specific features. The core idea is reusability—you build upon what already exists. Key Principle: Child Class =…

  • Negative lookbehind assertion

    A negative lookbehind assertion in Python’s re module is a zero-width assertion that checks if a pattern is not present immediately before the current position. It is written as (?<!…). It’s the opposite of a positive lookbehind and allows you to exclude matches based on what precedes them. Similar to the positive lookbehind, the pattern…

  • Alternation and Grouping

    Complete List of Alternation and Grouping in Python Regular Expressions Grouping Constructs Capturing Groups Pattern Description Example (…) Capturing group (abc) (?P<name>…) Named capturing group (?P<word>\w+) \1, \2, etc. Backreferences to groups (a)\1 matches “aa” (?P=name) Named backreference (?P<word>\w+) (?P=word) Non-Capturing Groups Pattern Description Example (?:…) Non-capturing group (?:abc)+ (?i:…) Case-insensitive group (?i:hello) (?s:…) DOTALL group (. matches…

  • What are Variables

    A program is essentially a set of instructions that tells a computer what to do. Just like a recipe guides a chef, a program guides a computer to perform specific tasks—whether it’s calculating numbers, playing a song, displaying a website, or running a game. Programs are written in programming languages like Python, Java, or C++,…

  • Static Methods

    The primary use of a static method in Python classes is to define a function that logically belongs to the class but doesn’t need access to the instance’s data (like self) or the class’s state (like cls). They are essentially regular functions that are grouped within a class namespace. Key Characteristics and Use Cases General…

Leave a Reply

Your email address will not be published. Required fields are marked *