🐍
← Back to Blog

Python Cashar 17 — Is-baaris: dir, type, help iyo docstrings

Python waxay kuu oggolaan in barnaamijku isagu is-weydiiyo: “maxaan ahay, maxaan sameyn karaa?” Tan waxaa loo yaqaan introspection, waxayna ku caawinaysaa markaad barato maktabad cusub.

type() iyo isinstance()

print(type(3), type(3.0), type('a'), type([1]))
print(isinstance(3, int))
print(isinstance(3.0, int))
print(isinstance(True, int))   # bool waa nooc int ah
<class 'int'> <class 'float'> <class 'str'> <class 'list'>
True
False
True

dir(): maxaa shay ku jira

dir(shay) wuxuu soo celiyaa liis magacyo ah oo uu shayga leeyahay (hawlaha iyo sifooyinka). Tusaale, si aad u aragto waxa qoraal sameyn karo:

hawlo = [m for m in dir('salaan') if not m.startswith('_')]
print(hawlo[:10])
print(len(hawlo))
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map']
47

Magacyada ku bilaabma laba xariiq hoose (dunder), sida __len__ ama __str__, waa magacyo sixir ah. Waxay hirgeliyaan hab-dhaqanka gudaha Python. Tusaale len(x) waxay gudaha ka wacdaa x.__len__().

x = [1, 2, 3]
print(len(x), x.__len__())
3 3

help() iyo docstrings

help(shay) wuxuu tusaa sharaxaad. Sharaxaaddu waxay ka timaadaa docstring ee shayga. Docstring waa qoraalka ugu horreeya ee ku jira hawl, class ama module.

print(len.__doc__)
print('---')
import math
print(math.sqrt.__doc__)
Return the number of items in a container.
---
Return the square root of x.
help(str.split)        # sharaxaadda hawlta split
help('modules')        # dhammaan modules la heli karo

Qor docstring wanaagsan

def hore(n):
    """Soo celi n tirooyinka ugu horreeya ee Fibonacci.

    Tusaale: hore(5) -> [0, 1, 1, 2, 3]
    """
    a, b, natiijo = 0, 1, []
    for _ in range(n):
        natiijo.append(a)
        a, b = b, a + b
    return natiijo

print(hore(8))
print(hore.__doc__)
[0, 1, 1, 2, 3, 5, 8, 13]
Soo celi n tirooyinka ugu horreeya ee Fibonacci.

    Tusaale: hore(5) -> [0, 1, 1, 2, 3]
    

Layli

  • Isticmaal dir() si aad u hesho hawlaha liiska ee aan bilaabmin _.
  • Qor hawl leh docstring, kadibna daabac .__doc__.
print([m for m in dir([]) if not m.startswith('_')])
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Soo koobid: type, isinstance, dir, help. Mar walba qor docstring hawlaha aad samayso.
Koorsada Python (20 cashar):
← Python Cashar 16 — Lambda, map, filter iyo list comprehension
Python Cashar 18 — NumPy: Arrays iyo xisaab degdeg ah →

Maqaallo Kale