Εκμάθηση Python 3 - Μάθετε την Python σε 30 λεπτά.

Το Python είναι μια ισχυρή γλώσσα προγραμματισμού ιδανική για scripting και γρήγορη ανάπτυξη εφαρμογών. Χρησιμοποιείται στην ανάπτυξη ιστού (όπως: Django and Bottle), επιστημονικός και μαθηματικός υπολογισμός (Orange, SymPy, NumPy) σε γραφικές διεπαφές χρήστη επιτραπέζιων υπολογιστών (Pygame, Panda3D).

Αυτό το σεμινάριο σας παρουσιάζει τις βασικές έννοιες και τα χαρακτηριστικά του Python 3. Αφού διαβάσετε το σεμινάριο, θα μπορείτε να διαβάσετε και να γράψετε βασικά προγράμματα Python και να εξερευνήσετε τη Python σε βάθος μόνοι σας.

Αυτό το σεμινάριο προορίζεται για άτομα που γνωρίζουν άλλες γλώσσες προγραμματισμού και θέλουν να ξεκινήσουν γρήγορα με το Python.

Python για αρχάριους

Εάν είστε αρχάριος προγραμματισμού, σας προτείνουμε να επισκεφτείτε:

  1. Προγραμματισμός Python - Ένας ολοκληρωμένος οδηγός για το τι είναι το Python, πώς να ξεκινήσετε στο Python, γιατί πρέπει να το μάθετε και πώς μπορείτε να το μάθετε.
  2. Tutorials Python - Ακολουθήστε τους συνδέσμους πλευρικής γραμμής ένας προς έναν.
  3. Παραδείγματα Python - Απλά παραδείγματα για αρχάριους.

Τι καλύπτεται σε αυτό το σεμινάριο;

  • Εκτελέστε το Python στον υπολογιστή σας
  • Εισαγωγή (Μεταβλητές, χειριστές, I / O,…)
  • Δομές δεδομένων (Λίστα, Λεξικό, Σύνολο,…)
  • Ροή ελέγχου (εάν, βρόχος, διακοπή,…)
  • Αρχείο (Διαχείριση αρχείων, Κατάλογος,…)
  • Εξαιρέσεις (Χειρισμός, Εξαίρεση καθορισμένη από τον χρήστη,…)
  • OOP (Αντικείμενο & κλάση, κληρονομικότητα, υπερφόρτωση,…)
  • Τυπική βιβλιοθήκη (Ενσωματωμένη λειτουργία, Μέθοδοι λίστας,…)
  • Διάφορα (Γεννήτριες, διακοσμητές,…)

Εκτελέστε το Python στον υπολογιστή σας

Δεν χρειάζεται να εγκαταστήσετε το Python στον υπολογιστή σας για να ακολουθήσετε αυτό το σεμινάριο. Ωστόσο, σας προτείνουμε να εκτελέσετε προγράμματα Python που περιλαμβάνονται σε αυτό το σεμινάριο στον δικό σας υπολογιστή.

  • Εκτελέστε το Python στα Windows
  • Εκτελέστε το Python σε MacOS

Εισαγωγή Python

Ας γράψουμε το πρώτο μας πρόγραμμα Python, "Hello, World!". Είναι ένα απλό πρόγραμμα που εκτυπώνει το Hello World! στην τυπική συσκευή εξόδου (οθόνη).

"Γειά σου Κόσμε!" Πρόγραμμα

 print("Hello, World!")

Όταν εκτελείτε το πρόγραμμα, η έξοδος θα είναι:

 Γειά σου Κόσμε!

Σε αυτό το πρόγραμμα, χρησιμοποιήσαμε την ενσωματωμένη λειτουργία εκτύπωσης () για την εκτύπωση Γεια, κόσμος! σειρά.

Μεταβλητές και λογοτεχνικά

Μια μεταβλητή είναι μια ονομαστική τοποθεσία που χρησιμοποιείται για την αποθήκευση δεδομένων στη μνήμη. Ακολουθεί ένα παράδειγμα:

 a = 5 

Εδώ, το a είναι μια μεταβλητή. Έχουμε εκχωρήσει 5στη μεταβλητή a

Δεν χρειάζεται να ορίσουμε μεταβλητό τύπο στο Python. Μπορείτε να κάνετε κάτι τέτοιο:

 a = 5 print("a =", 5) a = "High five" print("a =", a)

Αρχικά, η ακέραια τιμή 5αποδίδεται στη μεταβλητή a. Στη συνέχεια, η συμβολοσειρά High πέντε αντιστοιχεί στην ίδια μεταβλητή.

Παρεμπιπτόντως, 5είναι αριθμητική κυριολεκτική και "High five"είναι κυριολεκτική συμβολοσειρά.

Όταν εκτελείτε το πρόγραμμα, η έξοδος θα είναι:

 a = 5 a = Υψηλό πέντε 

Επισκεφτείτε τις μεταβλητές Python, Constants and Literals για να μάθετε περισσότερα.

Χειριστές

Οι χειριστές είναι ειδικά σύμβολα που εκτελούν λειτουργίες σε τελεστές (μεταβλητές και τιμές).

Ας μιλήσουμε για τους αριθμητικούς και τους τελεστές ανάθεσης σε αυτό το μέρος.

Οι αριθμητικοί τελεστές χρησιμοποιούνται για την εκτέλεση μαθηματικών πράξεων όπως προσθήκη, αφαίρεση, πολλαπλασιασμός κ.λπ.

 x = 14 y = 4 # Add two operands print('x + y =', x+y) # Output: x + y = 18 # Subtract right operand from the left print('x - y =', x-y) # Output: x - y = 10 # Multiply two operands print('x * y =', x*y) # Output: x * y = 56 # Divide left operand by the right one print('x / y =', x/y) # Output: x / y = 3.5 # Floor division (quotient) print('x // y =', x//y) # Output: x // y = 3 # Remainder of the division of left operand by the right print('x % y =', x%y) # Output: x % y = 2 # Left operand raised to the power of right (x^y) print('x ** y =', x**y) # Output: x ** y = 38416

Οι τελεστές ανάθεσης χρησιμοποιούνται για την εκχώρηση τιμών σε μεταβλητές. Έχετε ήδη δει τη χρήση του =χειριστή. Ας δοκιμάσουμε περισσότερους χειριστές ανάθεσης.

 x = 5 # x += 5 ----> x = x + 5 x +=5 print(x) # Output: 10 # x /= 5 ----> x = x / 5 x /= 5 print(x) # Output: 2.0

Άλλες συχνές φορέων ανάθεσης: -=, *=, %=, //=και **=.

Επισκεφτείτε το Python Operators για να μάθετε λεπτομερώς όλους τους χειριστές.

Λήψη εισόδου από το χρήστη

Στο Python, μπορείτε να χρησιμοποιήσετε τη συνάρτηση input () για να λάβετε είσοδο από τον χρήστη. Για παράδειγμα:

 inputString = input('Enter a sentence:') print('The inputted string is:', inputString) 

Όταν εκτελείτε το πρόγραμμα, η έξοδος θα είναι:

Εισαγάγετε μια πρόταση: Γεια σας. Η συμβολοσειρά που έχει εισαχθεί είναι: Γεια σας.

Σχόλια Python

Υπάρχουν 3 τρόποι δημιουργίας σχολίων στο Python.

 # Αυτό είναι ένα σχόλιο 
 "" Αυτό είναι ένα πολύπλευρο σχόλιο. "" " 
 '' Αυτό είναι επίσης ένα πολύπλευρο σχόλιο. '' ' 

Για να μάθετε περισσότερα σχετικά με τα σχόλια και το docstring, επισκεφθείτε: Σχόλια Python.

Τύπος μετατροπής

Η διαδικασία μετατροπής της τιμής ενός τύπου δεδομένων (ακέραιος, συμβολοσειρά, float κ.λπ.) σε έναν άλλο ονομάζεται μετατροπή τύπου. Η Python έχει δύο τύπους μετατροπής τύπου.

Σιωπηρή μετατροπή τύπου

Η σιωπηρή μετατροπή δεν χρειάζεται καμία συμμετοχή του χρήστη. Για παράδειγμα:

 num_int = 123 # integer type num_flo = 1.23 # float type num_new = num_int + num_flo print("Value of num_new:",num_new) print("datatype of num_new:",type(num_new))

Όταν εκτελείτε το πρόγραμμα, η έξοδος θα είναι:

 Τιμή num_new: 124.23 τύπος δεδομένων num_new: τύπος δεδομένων num_new: 

Εδώ, το num_new έχει τύπο δεδομένων float επειδή η Python μετατρέπει πάντα μικρότερο τύπο δεδομένων σε μεγαλύτερο τύπο δεδομένων για να αποφύγει την απώλεια δεδομένων.

Εδώ είναι ένα παράδειγμα όπου ο διερμηνέας Python δεν μπορεί να πληκτρολογήσει σιωπηρά μετατροπή.

 num_int = 123 # int type num_str = "456" # str type print(num_int+num_str)

Όταν εκτελείτε το πρόγραμμα, θα λάβετε

 TypeError: μη υποστηριζόμενοι τύποι τελεστών για +: 'int' και 'str'

Ωστόσο, η Python έχει μια λύση για αυτόν τον τύπο κατάστασης που είναι γνωστή ως ρητή μετατροπή.

Άμεση μετατροπή

Σε περίπτωση ρητής μετατροπής, μετατρέπετε τον τύπο δεδομένων ενός αντικειμένου στον απαιτούμενο τύπο δεδομένων. Χρησιμοποιούμε προκαθορισμένες συναρτήσεις, όπως int (), float (), str () κ.λπ. Για παράδειγμα:

 num_int = 123 # int type num_str = "456" # str type # explicitly converted to int type num_str = int(num_str) print(num_int+num_str)

Για να ακουμπήσετε περισσότερο, επισκεφτείτε τη μετατροπή τύπου Python.

Αριθμητικοί τύποι Python

Η Python υποστηρίζει ακέραιους αριθμούς, αριθμούς κινητής υποδιαστολής και σύνθετους αριθμούς. Ορίζονται ως int, floatκαι complexτάξη στο Python. Επιπλέον, τα booleans: Trueκαι Falseείναι ένας υποτύπος ακέραιων αριθμών.

 # Output: print(type(5)) # Output: print(type(5.0)) c = 5 + 3j # Output: print(type(c))

Για να μάθετε περισσότερα, επισκεφθείτε τους τύπους αριθμών Python.

Δομές δεδομένων Python

Η Python προσφέρει μια σειρά σύνθετων τύπων δεδομένων που συχνά αναφέρονται ως ακολουθίες. Θα μάθετε για αυτούς τους ενσωματωμένους τύπους σε αυτήν την ενότητα.

Τόπος αγώνων

Μια λίστα δημιουργείται τοποθετώντας όλα τα στοιχεία (στοιχεία) μέσα σε μια αγκύλη τετραγώνου ()διαχωρισμένη με κόμματα.

It can have any number of items and they may be of different types (integer, float, string etc.)

 # empty list my_list = () # list of integers my_list = (1, 2, 3) # list with mixed data types my_list = (1, "Hello", 3.4) 

You can also use list() function to create lists.

Here's how you can access elements of a list.

 language = ("French", "German", "English", "Polish") # Accessing first element print(language(0)) # Accessing fourth element print(language(3))

You use the index operator () to access an item in a list. Index starts from 0. So, a list having 10 elements will have index from 0 to 9.

Python also allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

Check these resources for more information about Python lists:

  • Python lists (slice, add and remove item etc.)
  • Python list methods
  • Python list comprehension

Tuples

Tuple is similar to a list except you cannot change elements of a tuple once it is defined. Whereas in a list, items can be modified.

Basically, list is mutable whereas tuple is immutable.

 language = ("French", "German", "English", "Polish") print(language)

You can also use tuple() function to create tuples.

You can access elements of a tuple in a similar way like a list.

 language = ("French", "German", "English", "Polish") print(language(1)) #Output: German print(language(3)) #Output: Polish print(language(-1)) # Output: Polish

You cannot delete elements of a tuple, however, you can entirely delete a tuple itself using del operator.

 language = ("French", "German", "English", "Polish") del language # NameError: name 'language' is not defined print(language)

To learn more, visit Python Tuples.

String

A string is a sequence of characters. Here are different ways to create a string.

 # all of the following are equivalent my_string = 'Hello' print(my_string) my_string = "Hello" print(my_string) my_string = '''Hello''' print(my_string) # triple quotes string can extend multiple lines my_string = """Hello, welcome to the world of Python""" print(my_string)

You can access individual characters of a string using indexing (in a similar manner like lists and tuples).

 str = 'programiz' print('str = ', str) print('str(0) = ', str(0)) # Output: p print('str(-1) = ', str(-1)) # Output: z #slicing 2nd to 5th character print('str(1:5) = ', str(1:5)) # Output: rogr #slicing 6th to 2nd last character print('str(5:-2) = ', str(5:-2)) # Output: am

Strings are immutable. You cannot change elements of a string once it is assigned. However, you can assign one string to another. Also, you can delete the string using del operator.

Concatenation is probably the most common string operation. To concatenate strings, you use + operator. Similarly, the * operator can be used to repeat the string for a given number of times.

 str1 = 'Hello ' str2 ='World!' # Output: Hello World! print(str1 + str2) # Hello Hello Hello print(str1 * 3)

Check these resources for more information about Python strings:

  • Python Strings
  • Python String Methods
  • Python String Formatting

Sets

A set is an unordered collection of items where every element is unique (no duplicates).

Here is how you create sets in Python.

 # set of integers my_set = (1, 2, 3) print(my_set) # set of mixed datatypes my_set = (1.0, "Hello", (1, 2, 3)) print(my_set)

You can also use set() function to create sets.

Sets are mutable. You can add, remove and delete elements of a set. However, you cannot replace one item of a set with another as they are unordered and indexing have no meaning.

Let's try commonly used set methods: add(), update() and remove().

 # set of integers my_set = (1, 2, 3) my_set.add(4) print(my_set) # Output: (1, 2, 3, 4) my_set.add(2) print(my_set) # Output: (1, 2, 3, 4) my_set.update((3, 4, 5)) print(my_set) # Output: (1, 2, 3, 4, 5) my_set.remove(4) print(my_set) # Output: (1, 2, 3, 5)

Let's tryout some commonly used set operations:

 A = (1, 2, 3) B = (2, 3, 4, 5) # Equivalent to A.union(B) # Also equivalent to B.union(A) print(A | B) # Output: (1, 2, 3, 4, 5) # Equivalent to A.intersection(B) # Also equivalent to B.intersection(A) print (A & B) # Output: (2, 3) # Set Difference print (A - B) # Output: (1) # Set Symmetric Difference print(A B) # Output: (1, 4, 5)

More Resources:

  • Python Sets
  • Python Set Methods
  • Python Frozen Set

Dictionaries

Dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. For example:

 # empty dictionary my_dict = () # dictionary with integer keys my_dict = (1: 'apple', 2: 'ball') # dictionary with mixed keys my_dict = ('name': 'John', 1: (2, 4, 3))

You can also use dict() function to create dictionaries.

To access value from a dictionary, you use key. For example:

 person = ('name':'Jack', 'age': 26, 'salary': 4534.2) print(person('age')) # Output: 26

Here's how you can change, add or delete dictionary elements.

 person = ('name':'Jack', 'age': 26) # Changing age to 36 person('age') = 36 print(person) # Output: ('name': 'Jack', 'age': 36) # Adding salary key, value pair person('salary') = 4342.4 print(person) # Output: ('name': 'Jack', 'age': 36, 'salary': 4342.4) # Deleting age del person('age') print(person) # Output: ('name': 'Jack', 'salary': 4342.4) # Deleting entire dictionary del person

More resources:

  • Python Dictionary
  • Python Dictionary Methods
  • Python Dictionary Comprehension

Python range()

range() returns an immutable sequence of numbers between the given start integer to the stop integer.

  print(range(1, 10)) # Output: range(1, 10) 

The output is an iterable and you can convert it to list, tuple, set and so on. For example:

 numbers = range(1, 6) print(list(numbers)) # Output: (1, 2, 3, 4, 5) print(tuple(numbers)) # Output: (1, 2, 3, 4, 5) print(set(numbers)) # Output: (1, 2, 3, 4, 5) # Output: (1: 99, 2: 99, 3: 99, 4: 99, 5: 99) print(dict.fromkeys(numbers, 99))

We have omitted optional step parameter for range() in above examples. When omitted, step defaults to 1. Let's try few examples with step parameter.

 # Equivalent to: numbers = range(1, 6) numbers1 = range(1, 6 , 1) print(list(numbers1)) # Output: (1, 2, 3, 4, 5) numbers2 = range(1, 6, 2) print(list(numbers2)) # Output: (1, 3, 5) numbers3 = range(5, 0, -1) print(list(numbers3)) # Output: (5, 4, 3, 2, 1)

Python Control Flow

if… else Statement

The if… else statement is used if you want perform different action (run different code) on different condition. For example:

 num = -1 if num> 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") # Output: Negative number

There can be zero or more elif parts, and the else part is optional.

Most programming languages use () to specify the block of code. Python uses indentation.

A code block starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.

Generally, four whitespace is used for indentation and is preferred over tabs.

Let's try another example:

 if False: print("I am inside the body of if.") print("I am also inside the body of if.") print("I am outside the body of if") # Output: I am outside the body of if.

Before you move on to next section, we recommend you to check comparison operator and logical operator.

Also, check out Python if… else in detail.

while Loop

Like most programming languages, while loop is used to iterate over a block of code as long as the test expression (condition) is true. Here is an example to find the sum of natural numbers:

 n = 100 # initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # update counter print("The sum is", sum) # Output: The sum is 5050

In Python, while loop can have optional else block that is executed if the condition in the while loop evaluates to False. However, if the loop is terminated with break statement, Python interpreter ignores the else block.

To learn more, visit Python while Loop

for Loop

In Python, for loop is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.

Here's an example to find the sum of all numbers stored in a list.

 numbers = (6, 5, 3, 8, 4, 2) sum = 0 # iterate over the list for val in numbers: sum = sum+val print("The sum is", sum) # Output: The sum is 28

Notice the use of in operator in the above example. The in operator returns True if value/variable is found in the sequence.

In Python, for loop can have optional else block. The else part is executed if the items in the sequence used in for loop exhausts. However, if the loop is terminated with break statement, Python interpreter ignores the else block.

To learn more, visit Python for Loop

break Statement

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. For example:

 for val in "string": if val == "r": break print(val) print("The end")

When you run the program, the output will be:

 s t The end 

continue Statement

The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. For example:

 for val in "string": if val == "r": continue print(val) print("The end")

When you run the program, the output will be:

 s t i n g The end 

To learn more on break and continue with detail explanation, visit Python break and continue.

pass Statement

Suppose, you have a loop or a function that is not implemented yet, but want to implement it in the future. They cannot have an empty body. The interpreter would complain. So, you use the pass statement to construct a body that does nothing.

 sequence = ('p', 'a', 's', 's') for val in sequence: pass

Python Function

A function is a group of related statements that perform a specific task. You use def keyword to create functions in Python.

 def print_lines(): print("I am line1.") print("I am line2.") 

You have to call the function to run the codes inside it. Here's how:

 def print_lines(): print("I am line1.") print("I am line2.") # function call print_lines()

A function can accept arguments.

 def add_numbers(a, b): sum = a + b print(sum) add_numbers(4, 5) # Output: 9

You can also return value from a function using return statement.

 def add_numbers(a, b): sum = a + b return sum result = add_numbers(4, 5) print(result) # Output: 9

Here are few resources to check:

  • Python Function
  • Python Function Arguments (Default, Keyword, Arbitrary)

Recursion (Recursive function)

A function that calls itself is known as recursive function and this process is called recursion.

Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely.

 # Recursive function to find the factorial of a number def calc_factorial(x): if x == 1: return 1 else: return (x * calc_factorial(x-1)) num = 6 print("The factorial of", num, "is", calc_factorial(num)) # Output: The factorial of 6 is 720

Visit Python recursion to learn more.

Lambda Function

In Python, you can define functions without a name. These functions are called lambda or anonymous function. To create a lambda function, lambda keyword is used.

 square = lambda x: x ** 2 print(square(5)) # Output: 25

We use lambda functions when we require a nameless function for a short period of time. Lambda functions are used along with built-in functions like filter(), map() etc.

To learn more, visit:

  • Python Lambda Function
  • Python map()
  • Python filter()

Modules

Modules refer to a file containing Python statements and definitions.

A file containing Python code, for e.g.: example.py, is called a module and its module name would be example.

Let us create it and save it as example.py.

 # Python Module example def add(a, b): return a + b 

To use this module, we use import keyword.

 # importing example module import example # accessing the function inside the module using . operator example.add(4, 5.5) 

Python has a ton of standard modules readily available for use. For example:

 import math result = math.log2(5) # return the base-2 logarithm print(result) # Output: 2.321928094887362

You can import specific names from a module without importing the module as a whole. Here is an example.

 from math import pi print("The value of pi is", pi) # Output: The value of pi is 3.141592653589793

More Resources:

  • Python Modules
  • Python Packages

Python File I/O

A file operation takes place in the following order.

  1. Open a file
  2. Read or write (perform operation)
  3. Close the file

How to open a file?

You can use open() function to open a file.

 f = open("test.txt") # open file in current directory f = open("C:/Python33/README.txt") # specifying full path 

We can specify the mode while opening a file.

Mode Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
 f = open("test.txt") # equivalent to 'r' or 'rt' f = open("test.txt",'w') # write in text mode f = open("img.bmp.webp",'r+b') # read and write in binary mode 

How to close a file?

To close a file, you use close() method.

 f = open("test.txt",encoding = 'utf-8') # perform file operations f.close() 

How to write to a file?

In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive creation 'x' mode.

 with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file") f.write("This file") f.write("contains three lines") 

Here, we have used with statement to open a file. This ensures that the file is closed when the block inside with is exited.

How to read files?

To read a file in Python, you must open the file in reading mode.

There are various methods available for this purpose. We can use the read(size) method to read in size number of data.

 f = open("test.txt",'r',encoding = 'utf-8') f.read(4) # read the first 4 data 

Visit Python File I/O to learn more.

Python Directory

A directory or folder is a collection of files and sub directories. Python has the os module, which provides many useful methods to work with directories and files.

 import os os.getcwd() // present working directory os.chdir('D:\Hello') // Changing current directory to D:Hello os.listdir() // list all sub directories and files in that path os.mkdir('test') // making a new directory test os.rename('test','tasty') // renaming the directory test to tasty os.remove('old.txt') // deleting old.txt file 

Visit Python Directory to learn more.

Python Exception Handling

Errors that occur at runtime are called exceptions. They occur, for example, when a file we try to open does not exist FileNotFoundError, dividing a number by zero ZeroDivisionError etc.

Visit this page to learn about all built-in exceptions in Python.

If exceptions are not handled, an error message is spit out and our program come to a sudden, unexpected halt.

In Python, exceptions can be handled using try statement. When exceptions are caught, it's up to you what operator to perform.

 # import module sys to get the type of exception import sys randomList = ('a', 0, 2) for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except: print("Oops!",sys.exc_info()(0),"occurred.") print("Next entry.") print() print("The reciprocal of",entry,"is",r)

When you run the program, the output will be:

 The entry is a Oops! occurred. Next entry. The entry is 0 Oops! occurred. Next entry. The entry is 2 The reciprocal of 2 is 0.5

To learn about catching specific exceptions and finally clause with try statement, visit Python exception handling.

Also, you can create user-defined exceptions in Python. For that, visit Python Custom Exceptions

Python OOP

Everything in Python is an object including integers, floats, functions, classes, and None. Let's not focus on why everything in Python is an object. For that, visit this page. Rather, this section focuses on creating your own classes and objects.

Class and Objects

Object is simply a collection of data (variables) and methods (functions) that act on data. And, class is a blueprint for the object.

How to define a class?

 class MyClass: a = 10 def func(self): print('Hello') 

As soon as you define a class, a new class object is created with the same name. This class object allows us to access the different attributes as well as to instantiate new objects of that class.

 class MyClass: "This is my class" a = 10 def func(self): print('Hello') # Output: 10 print(MyClass.a) # Output: print(MyClass.func) # Output: 'This is my class' print(MyClass.__doc__)

You may have noticed the self parameter in function definition inside the class but, we called the method simply as ob.func() without any arguments. It still worked.

This is because, whenever an object calls its method, the object itself is passed as the first argument. So, ob.func() translates into MyClass.func(ob).

Creating Objects

You can also create objects of the class yourself.

 class MyClass: "This is my class" a = 10 def func(self): print('Hello') obj1 = MyClass() print(obj1.a) # Output: 10 obj2 = MyClass() print(obj1.a + 5) # Output: 15

Python Constructors

In Python, a method with name __init()__ is a constructor. This method is automatically called when an object is instantiated.

 class ComplexNumber: def __init__(self,r = 0,i = 0): # constructor self.real = r self.imag = i def getData(self): print("(0)+(1)j".format(self.real,self.imag)) c1 = ComplexNumber(2,3) # Create a new ComplexNumber object c1.getData() # Output: 2+3j c2 = ComplexNumber() # Create a new ComplexNumber object c2.getData() # Output: 0+0j

Visit Python Class and Object to learn more.

Python Inheritance

Inheritance refers to defining a new class with little or no modification to an existing class. Let's take an example:

 class Mammal: def displayMammalFeatures(self): print('Mammal is a warm-blooded animal.')

Let's derive a new class Dog from this Mammal class.

 class Mammal: def displayMammalFeatures(self): print('Mammal is a warm-blooded animal.') class Dog(Mammal): def displayDogFeatures(self): print('Dog has 4 legs.') d = Dog() d.displayDogFeatures() d.displayMammalFeatures()

Notice that we are able to call method of base class displayMammalFeatures() from the object of derived class d.

To learn more about inheritance and method overriding, visit Python Inheritance.

We also suggest you to check multiple inheritance and operator overloading if you are interested.

Miscellaneous and Advance Topics

Iterators

Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time.

Technically speaking, Python iterator object must implement two special methods, __iter__() and __next__(), collectively called the iterator protocol.

An object is called iterable if we can get an iterator from it. Most of built-in containers in Python like: list, tuple, string etc. are iterables.

The iter() function (which in turn calls the __iter__() method) returns an iterator from them.

 my_list = (4, 7, 0, 3) # get an iterator using iter() my_iter = iter(my_list) print(next(my_iter)) # Output: 4 print(next(my_iter)) # Output: 7

To learn more about infinite iterators and how to create custom iterators, visit: Python Iterators.

Generators

There is a lot of overhead in building an iterator in Python; we have to implement a class with __iter__() and __next__() method, keep track of internal states, raise StopIteration when there was no values to be returned etc.

This is both lengthy and counter intuitive. Generator comes into rescue in such situations.

Python generators are a simple way of creating iterators.

Learn more about Python Generators.

Closures

This technique by which some data gets attached to the code is called closure in Python.

 def print_msg(msg): # outer enclosing function def printer(): # inner function print(msg) return printer # this got changed another = print_msg("Hello") # Output: Hello another()

Here, the print_msg() function is called with the string "Hello" as an argument and the returned function was bound to the name another. On calling another(), the message was still remembered although we had already finished executing the print_msg() function.

The criteria that must be met to create closure in Python are summarized in the following points.

  • We must have a nested function (function inside a function).
  • The nested function must refer to a value defined in the enclosing function.
  • The enclosing function must return the nested function.

Visit Python closures to learn more about closures and when to use them.

Decorators

Python has an interesting feature called decorators to add functionality to an existing code.

Αυτό ονομάζεται επίσης μεταπρογραμματισμός καθώς ένα μέρος του προγράμματος προσπαθεί να τροποποιήσει ένα άλλο μέρος του προγράμματος τη στιγμή της μεταγλώττισης.

Για να μάθετε λεπτομερώς για τους διακοσμητές, επισκεφθείτε το Python Decorators.

Έχασα τίποτα σε αυτό το σεμινάριο Python;

ενδιαφέροντα άρθρα...