„Python“ instrukcijos (su pavyzdžiais)

Šioje pamokoje sužinosime apie „Python“ instrukcijas. Konkrečiau, naudodamiesi pavyzdžiais sužinosime, kaip ir kodėl naudojamos instrukcijos.

„Python“ instrukcijos yra eilutės literalai, atsirandantys iškart po funkcijos, metodo, klasės ar modulio apibrėžimo. Paimkime pavyzdį.

1 pavyzdys: Instrukcijos

 def square(n): '''Takes in a number n, returns the square of n''' return n**2

Čia eilutė pažodžiui:

 Įgauna skaičių n, grąžina n kvadratą

Trigubose kabutėse yra funkcijos dokstringas , kuris square()pasirodo iškart po jo apibrėžimo.

Pastaba: Mes taip pat galime naudoti trigubas """citatas kurdami instrukcijas.

„Python“ komentarai ir „Docstrings“

„Python“ komentarai

Komentarai yra aprašymai, kurie padeda programuotojams geriau suprasti programos tikslą ir funkcionalumą. Jas „Python“ vertėjas visiškai ignoruoja.

„Python“ naudojame maišos simbolį #vienos eilutės komentarui parašyti. Pavyzdžiui,

 # Program to print "Hello World" print("Hello World") 

„Python“ komentarai naudojant eilutes

Jei nė vienam kintamajam nepriskiriame eilučių, jie veikia kaip komentarai. Pavyzdžiui,

 "I am a single-line comment" ''' I am a multi-line comment! ''' print("Hello World")

Pastaba: kelių eilučių eilutėms naudojame trigubas kabutes.

„Python“ instrukcijos

Kaip minėta pirmiau, „Python“ instrukcijos yra eilutės, naudojamos iškart po funkcijos, metodo, klasės ar modulio apibrėžimo (kaip 1 pavyzdyje ). Jie naudojami dokumentuoti mūsų kodą.

Šias dokstringas galime pasiekti naudodami __doc__atributą.

Python __doc__ atributas

Kai eilutės literalai yra tik apibrėžę funkciją, modulį, klasę ar metodą, jie yra susieti su objektu kaip jų __doc__atributu. Vėliau mes galime naudoti šį atributą, kad gautume šią instrukciją.

2 pavyzdys: Spausdinimo instrukcija

 def square(n): '''Takes in a number n, returns the square of n''' return n**2 print(square.__doc__)

Rezultatas

 Gauna skaičių n, grąžina n kvadratą

Čia prie mūsų square()funkcijos dokumentacijos galima susipažinti naudojant __doc__atributą.

Dabar pažvelkime į integruotos funkcijos instrukcijas print():

3 pavyzdys: Integruotos spausdinimo () funkcijos instrukcijos

 print(print.__doc__)

Rezultatas

spausdinti (reikšmė,…, sep = '', end = ' n', file = sys.stdout, flush = False) Pagal numatytuosius nustatymus spausdina reikšmes srautui arba sys.stdout. Pasirenkami raktinių žodžių argumentai: failas: į failą panašus objektas (srautas); pagal numatytuosius nustatymus yra dabartinis sys.stdout. sep: eilutė įterpta tarp reikšmių, numatytasis tarpas. pabaiga: eilutė pridėta po paskutinės reikšmės, numatytoji nauja eilutė. nuplauti: ar priverstinai nuplauti srovę.

Čia galime pamatyti, kad print()funkcijos dokumentacija yra šios funkcijos __doc__atributas.

Vienos eilutės instrukcijos „Python“

Vienos eilutės instrukcijos yra dokumentai, kurie telpa vienoje eilutėje.

Standartiniai vienos eilutės instrukcijų rašymo principai:

  • Nors jie yra vienos eilutės, mes vis dar naudojame trigubas kabutes aplink šias instrukcijas, nes vėliau jas galima lengvai išplėsti.
  • Baigiamosios kabutės yra toje pačioje eilutėje kaip ir pradžios kabutės.
  • Nei prieš dokstringą, nei po jo nėra tuščios eilutės.
  • Jie neturėtų būti aprašomieji, jie turi laikytis struktūros „Padaryk tai, grąžink tą“ struktūrą, pasibaigiantį tašku.

Paimkime pavyzdį.

4 pavyzdys: parašykite vienos eilutės funkcijos nurodymus

 def multiplier(a, b): """Takes in two numbers, returns their product.""" return a*b

„Multi-line Docstrings“ „Python“

Kelių eilučių instrukcijas sudaro santraukos eilutė, kaip ir vienos eilutės eilutė, po kurios eina tuščia eilutė, po kurios pateikiamas išsamesnis aprašymas.

Dokumente PEP 257 pateikiamos standartinės konvencijos, kaip rašyti kelių eilučių instrukcijas įvairiems objektams.

Kai kurie buvo išvardyti žemiau:

1. Python modulių instrukcijos

  • „Python“ modulių instrukcijose turėtų būti išvardytos visos galimos klasės, funkcijos, objektai ir išimtys, kurios yra importuojamos importuojant modulį.
  • They should also have a one-line summary for each item.

They are written at the beginning of the Python file.

Let's look at the docstrings for the builtin module in Python called pickle.

Example 4: Docstrings of Python module

 import pickle print(pickle.__doc__)

Output

 Create portable serialized representations of Python objects. See module copyreg for a mechanism for registering custom picklers. See module pickletools source for extensive comments. Classes: Pickler Unpickler Functions: dump(object, file) dumps(object) -> string load(file) -> object loads(string) -> object Misc variables: __version__ format_version compatible_formats

Here, we can see that the docstring written at the beginning of the pickle.py module file can be accessed as its docstring.

2. Docstrings for Python Functions

  • The docstring for a function or method should summarize its behavior and document its arguments and return values.
  • It should also list all the exceptions that can be raised and other optional arguments.

Example 5: Docstrings for Python functions

 def add_binary(a, b): ''' Returns the sum of two decimal numbers in binary digits. Parameters: a (int): A decimal integer b (int): Another decimal integer Returns: binary_sum (str): Binary string of the sum of a and b ''' binary_sum = bin(a+b)(2:) return binary_sum print(add_binary.__doc__)

Output

 Returns the sum of two decimal numbers in binary digits. Parameters: a (int): A decimal integer b (int): Another decimal integer Returns: binary_sum (str): Binary string of the sum of a and b

As you can see, we have included a short description of what the function does, the parameter it takes in and the value it returns. The string literal is embedded to the function add_binary as its __doc__ attribute.

3. Docstrings for Python Classes

  • The docstrings for classes should summarize its behavior and list the public methods and instance variables.
  • The subclasses, constructors, and methods should each have their own docstrings.

Example 6: Docstrings for Python class

Suppose we have a Person.py file with the following code:

 class Person: """ A class to represent a person.… Attributes ---------- name : str first name of the person surname : str family name of the person age : int age of the person Methods ------- info(additional=""): Prints the person's name and age. """ def __init__(self, name, surname, age): """ Constructs all the necessary attributes for the person object. Parameters ---------- name : str first name of the person surname : str family name of the person age : int age of the person """ self.name = name self.surname = surname self.age = age def info(self, additional=""): """ Prints the person's name and age. If the argument 'additional' is passed, then it is appended after the main info. Parameters ---------- additional : str, optional More info to be displayed (default is None) Returns ------- None """ print(f'My name is (self.name) (self.surname). I am (self.age) years old.' + additional)

Here, we can use the following code to access only the docstrings of the Person class:

 print(Person.__doc__)

Output

 A class to represent a person.… Attributes ---------- name : str first name of the person surname : str family name of the person age : int age of the person Methods ------- info(additional=""): Prints the person's name and age

Using the help() Function for Docstrings

We can also use the help() function to read the docstrings associated with various objects.

Example 7: Read Docstrings with the help() function

We can use the help() function on the class Person in Example 6 as:

 help(Person)

Output

 Help on class Person in module __main__: class Person(builtins.object) | Person(name, surname, age) | | A class to represent a person. | |… | | Attributes | ---------- | name : str | first name of the person | surname : str | family name of the person | age : int | age of the person | | Methods | ------- | info(additional=""): | Prints the person's name and age. | | Methods defined here: | | __init__(self, name, surname, age) | Constructs all the necessary attributes for the person object. | | Parameters | ---------- | name : str | first name of the person | surname : str | family name of the person | age : int | age of the person | | info(self, additional='') | Prints the person's name and age. | | If the argument 'additional' is passed, then it is appended after the main info. | | Parameters | ---------- | additional : str, optional | More info to be displayed (default is None) | | Returns | ------- | None | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined)

Here, we can see that the help() function retrieves the docstrings of the Person class along with the methods associated with that class.

4. Docstrings for Python Scripts

  • The docstrings for Python script should document the script's functions and command-line syntax as a usable message.
  • It should serve as a quick reference to all the functions and arguments.

5. Docstrings for Python Packages

The docstrings for a Python package is written in the package's __init__.py file.

  • It should contain all the available modules and sub-packages exported by the package.

Docstring Formats

We can write docstring in many formats like the reStructured text (reST) format, Google format or the NumPy documentation format. To learn more, visit Popular Docstring Formats

Mes taip pat galime generuoti dokumentaciją iš docstring'ų, naudodami tokius įrankius kaip Sfinksas. Norėdami sužinoti daugiau, apsilankykite oficialioje sfinkso dokumentacijoje

Įdomios straipsniai...