Pythoni käsklused (koos näidetega)

Selles õpetuses õpime tundma Pythoni käske. Täpsemalt õpime näidete abil, kuidas ja miks kasutatakse käske.

Pythoni käsustringid on stringiliitrid, mis ilmuvad kohe pärast funktsiooni, meetodi, klassi või mooduli määratlust. Võtame näite.

Näide 1: käsuliinid

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

Siin on sõna otsesõnaline string:

 '' 'Sisestab arvu n, tagastab ruudu n' ''

Kolmekordsete jutumärkide sees on funktsiooni käsk , square()nagu see ilmub kohe pärast selle määratlust.

Märkus""" . Dokstringide loomiseks võime kasutada ka kolmiktsitaate.

Pythoni kommentaarid vs käsuread

Pythoni kommentaarid

Kommentaarid on kirjeldused, mis aitavad programmeerijatel paremini mõista programmi eesmärki ja funktsionaalsust. Pythoni tõlk ignoreerib neid täielikult.

Pythonis kasutame #ühe rea kommentaari kirjutamiseks räsi sümbolit . Näiteks,

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

Pythoni kommentaarid stringide abil

Kui me ei määra ühelegi muutujale stringe, toimivad need kommentaaridena. Näiteks,

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

Märkus . Mitmerealiste stringide jaoks kasutame kolmikjutumärke.

Pythoni käsklused

Nagu eespool mainitud, on Pythoni käsustringid stringid, mida kasutatakse kohe pärast funktsiooni, meetodi, klassi või mooduli määratlust (nagu näites 1 ). Neid kasutatakse meie koodi dokumenteerimiseks.

Nendele käskudele pääseme juurde __doc__atribuudi abil.

Atribuut Python __doc__

Alati, kui stringi literaalid esinevad vahetult pärast funktsiooni, mooduli, klassi või meetodi määratlemist, seostatakse nad objektiga nende __doc__atribuudina. Hiljem saame seda atribuuti selle käsu toomiseks kasutada.

Näide 2: Dokstringi printimine

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

Väljund

 Võtab arvu n, tagastab ruudu n

Meie square()funktsiooni dokumentatsioonile pääseb juurde __doc__atribuudi abil.

Vaatame nüüd sisseehitatud funktsiooni käske print():

Näide 3: Sisseehitatud print () funktsiooni käsustringid

 print(print.__doc__)

Väljund

print (väärtus,…, sep = '', end = ' n', file = sys.stdout, flush = vale) Prindib väärtused vaikimisi voosse või sys.stdout. Valikulised märksõnaargumendid: fail: failitaoline objekt (voog); vaikimisi praegune sys.stdout. sep: string lisatakse väärtuste vahele, vaikimisi tühik. end: string lisatakse pärast viimast väärtust, vaikimisi uus rida. loputamine: kas voolu sunniviisiliselt loputada.

Siin näeme, et print()funktsiooni dokumentatsioon on selle funktsiooni __doc__atribuudina.

Üherealised käsklused Pythonis

Üherealised käsklused on dokumendid, mis sobivad ühte ritta.

Üherealiste käskude kirjutamise tavapärased kokkulepped:

  • Kuigi need on ühe joonega, kasutame nende käskude ümber siiski kolmikjutumärke, kuna neid saab hiljem hõlpsalt laiendada.
  • Lõpppakkumised asuvad samal joonel alguspakkumistega.
  • Ei enne ega pärast dokstringi pole tühja rida.
  • Need ei tohiks olla kirjeldavad, pigem peavad nad järgima struktuuri, mis lõpeb perioodiga, "Tehke seda, tagastage see".

Võtame näite.

Näide 4: funktsiooni jaoks kirjutage üherealised käskkirjad

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

Mitmerealine käsurida Pythonis

Mitmerealised käsuliinid koosnevad kokkuvõtlikust reast nagu üherealised, millele järgneb tühi rida, millele järgneb täpsem kirjeldus.

Dokument PEP 257 pakub standardsed kokkulepped mitmerealiste käskude kirjutamiseks erinevate objektide jaoks.

Mõned neist on loetletud allpool:

1. Pythoni moodulite käsklused

  • Pythoni moodulite käskkirjad peaksid loetlema kõik saadaolevad klassid, funktsioonid, objektid ja erandid, mis imporditakse mooduli importimisel.
  • 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

Samuti saame dokumente genereerida dokstringidest, kasutades selliseid tööriistu nagu Sphinx. Lisateabe saamiseks külastage ametlikku sfinksi dokumentatsiooni

Huvitavad Artiklid...