Самоанализ кода в Python

Опубликовано: 4 Февраля, 2022

Introspection is an ability to determine the type of an object at runtime. Everything in python is an object. Every object in Python may have attributes and methods. By using introspection, we can dynamically examine python objects. Code Introspection is used for examining the classes, methods, objects, modules, keywords and get information about them so that we can utilize it. Introspection reveals useful information about your program’s objects. Python, being a dynamic, object-oriented programming language, provides tremendous introspection support. Python’s support for introspection runs deep and wide throughout the language.
Python provides some built-in functions that are used for code introspection.They are:
1.type() : This function returns the type of an object.

# Python program showing
# a use of type function
  
import math
  
# print type of math
print(type(math))
   
# print type of 1 
print(type(1))
  
# print type of "1"
print(type("1"))
  
# print type of rk
rk =[1, 2, 3, 4, 5, "radha"]
  
print(type(rk))
print(type(rk[1]))
print(type(rk[5]))

Выход:

 <класс 'модуль'>
<класс 'int'>
<класс 'str'>
<список классов>
<класс 'int'>
<класс 'str'>

 
2.dir() :This function return list of methods and attributes associated with that object.

# Python program showing
# a use of dir() function
  
import math
rk =[1, 2, 3, 4, 5]
  
# print methods and attributes of rk
print(dir(rk))
rk =(1, 2, 3, 4, 5)
  
# print methods and attributes of rk
print(dir(rk))
rk ={1, 2, 3, 4, 5}
  
print(dir(rk))
print(dir(math))
Output:
["__add__", "__class__", "__contains__", "__delattr__", "__delitem__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__gt__", "__hash__", "__iadd__", "__imul__", "__init__", "__iter__", "__le__", "__len__", "__lt__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__rmul__", "__setattr__", "__setitem__", "__sizeof__", "__str__", "__subclasshook__", "append", "clear", "copy", "count", "extend", "index", "insert", "pop", "remove", "reverse", "sort"]
["__add__", "__class__", "__contains__", "__delattr__", "__dir__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__getnewargs__", "__gt__", "__hash__", "__init__", "__iter__", "__le__", "__len__", "__lt__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__rmul__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "count", "index"]
["__doc__", "__loader__", "__name__", "__package__", "__spec__", "acos", "acosh", "asin", "asinh", "atan", "atan2", "atanh", "ceil", "copysign", "cos", "cosh", "degrees", "e", "erf", "erfc", "exp", "expm1", "fabs", "factorial", "floor", "fmod", "frexp", "fsum", "gamma", "gcd", "hypot", "inf", "isclose", "isfinite", "isinf", "isnan", "ldexp", "lgamma", "log", "log10", "log1p", "log2", "modf", "nan", "pi", "pow", "radians", "sin", "sinh", "sqrt", "tan", "tanh", "trunc"]

 
3.str() :This function converts everything into a string .

# Python program showing
# a use of str() function
  
a = 1
print(type(a))
  
# converting integer
# into string
a = str(a)
print(type(a))
  
s =[1, 2, 3, 4, 5]
print(type(s))
  
# converting list
# into string
s = str(s)
print(type(s))

Выход:

 <класс 'int'>
<класс 'str'>
<список классов>
<класс 'str'>

 
4.id() :This function returns a special id of an object.

# Python program showing
# a use of id() function
   
import math
a =[1, 2, 3, 4, 5]
   
# print id of a
print(id(a))
b =(1, 2, 3, 4, 5)
   
# print id of b
print(id(b))
c ={1, 2, 3, 4, 5}
   
# print id of c
print(id(c))
print(id(math))

Выход:

139787756828232
139787757942656
139787757391432
139787756815768

Методы интроспекции кода

Функция Описание
помощь() Он используется, чтобы узнать, что делают другие функции.
hasattr () Проверяет, есть ли у объекта атрибут
getattr () Возвращает содержимое атрибута, если оно есть.
repr () Вернуть строковое представление объекта
вызываемый () Проверяет, является ли объект вызываемым объектом (функцией) или нет.
issubclass () Проверяет, является ли конкретный класс производным от другого класса.
isinstance () Проверяет, является ли объект экземпляром определенного класса.
sys () Предоставлять доступ к системным переменным и функциям
__doc__ Вернуть некоторую документацию об объекте
__имя__ Вернуть имя объекта.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.