04 OCT 2019

Grid: Grid geometry manager puts the widgets in a 2-dimensional table. The master widget is split into a number of rows and columns, and each “cell” in the resulting table can hold a widget … full article

grid1.PNG

Entry validation: to restrict the characters that can be typed into an entry widget, only numbers for instance, a validate command can be added to the entry. A validate command is a function that return True if the change is accepted, False otherwise. This function will be called each time the content of the entry is modified full article

Radio button: the Radiobutton is a standard Tkinter widget used to implement one-of-many selections. Radiobuttons can contain text or images, and you can associate a Python function or method with each button. When the button is pressed, Tkinter automatically calls that function or method. The button can only display text in a single font, but the text may span more than one line. In addition, one of the characters can be underlined, for example to mark a keyboard shortcut. By default, the Tab key can be used to move to a button widget … full article

Listbox: the Listbox widget is a standard Tkinter widget used to display a list of alternatives. The listbox can only contain text items, and all items must have the same font and color. Depending on the widget configuration, the user can choose one or more alternatives from the list … full article

Bind: tkinter provides a powerful mechanism to let you deal with events yourself. For each widget, you can bind Python functions and methods to events … full article

widget.bind(event, handler)

Project II – file manager:

fileman2.png

click here to download the project

More topics covered:

  • Entry can use var such as StringVar 
  • Entry trick to notice text change
  • RadioButton set indicatoron=0
  • Listbox – selected items
  • Listbox – add remove
  • Listbox – mouse mouse

Links:

27 SEP 2019

Lambda functions: Python allows you to create anonymous function i.e function having no names using a facility called lambda function. lambda functions are small functions not more than a line. It can have any number of arguments just like a normal function. The body of lambda functions is very small and consists of only one expression. The result of the expression is the value when the lambda is applied to an argument. Also there is no need for any return statement in lambda function.

lambda1

filter1

map1

The Variable Classes (BooleanVar, DoubleVar, IntVar, StringVar)
You can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified. or modify the value your self … full artice

More topics covered:

  • lambda with multiple arguments
  • lambda expression into tkinter
  • import time and time.ctime()
  • placing window widget on self

Links:

13 SEP 2019

At the class level, variables are referred to as class variables (static data), whereas variables at the instance level are called instance variables. When we expect variables are going to be consistent across instances, or when we would like to initialize a variable, we can define that variable at the class level. When we anticipate the variables will change significantly across instances, we can define them at the instance level. Defined outside of all the methods, class variables are, by convention, typically placed right below the class header and before the constructor method and other methods.

class_var.PNG

staticmethod (@staticmethod) is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. 

classmethod (@classmethod), is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Class methods are also used as an alternative constructors- for example from_string which creates as instance of the class from a string variable

TKinter: is the Python GUI toolkit. Tkinter is included with standard Linux, Microsoft Windows and Mac OS X installs of Python.

tkinter_code.PNG

tkinter.PNG

More topics covered:

  • static data
  • static – without self
  • static – fromlist
  • TKinter fonts
  • TKinter button styles
  • TKinter Implement a window class
  • mainloop – blocking method

Links:

06 SEP 2019

OS functions: 
getcwd – get current working directory
chdir – change current directory 
listdir – print all files in current directory
makedirs – create folders (and sub folder) 
mkdir – create folder (without sub folder)
stat.st_mtime – get file last modification time
stat.size – get file size
walk – get all files, folders in a folder (recursion)
getenv – get system variables (i.e. PATH)
startfile – start a process
path.isfile – check if a path is a file
path.isdir – check if a path is a directory
path.exists – check if a path exists or not
os.path.join – combine a folder name with a file name
os.path.splitext – separates file name from its extension

shutil library: 
rmtree – remove folder and all of its context

psutil library:
process_iter – get all processed

datetime library:
now – get the current date and time
fromtimestamp – converts a time stamp into a date time

More topics covered:

  • Task manager
  • Running os command from shell
  • static variables introduction

Links:

30 AUG 2019

exhr.png

Exception: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions during the execution of a program. When an error occurs within a method, the method creates an object and hands it off to the python runtime. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the python runtime s called throwing an exception. After a method throws an exception, the python runtime attempts to find something to handle it. The set of possible “somethings” to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program’s response to any exceptions in the preceding tryclause. You can attach a finally-clause to a try-except block. The code inside the finally clause will always be executed, even if an exception is thrown from within the try or except block. If your code has a return statement inside the try or except block, the code inside the finally-block will get executed before returning from the method. 

Import statement: In Python, modules are accessed by using the import statement. When you do this, you execute the code of the module, keeping the scopes of the definitions so that your current file(s) can make use of these. When Python imports a module called hello for example, the interpreter will first search for a built-in module called hello. If a built-in module is not found, the Python interpreter will then search for a file named hello.py in the current folder 

OS functions:
getcwd – get current working directory
chdir – change current directory 
listdir – print all files in current directory
mkdir – create folder (without sub folder)

More topics covered:

  • try-except-finally
  • Exception tree Hierarchy
  • Inner exception
  • Multiple except statement
  • catch vs except
  • except Exception as e
  • try-except for user input (i.e. int)
  • API class
  • Static method
  • if __name__ == __main__ …

Links:

23 AUG 2019

Class properties as __dict__: we saw that all of the properties in a class are stored in a dictionary property called __dict__. whenever we add a property to the object (i.e. using self.name = name) then the property (‘name’ [and its value]) is added into this dictionary (__dict__). this gives us the flexibility of adding properties into the class dynamically- by simply adding entries into __dict__ (or even set the dictionary as a whole). this could also assist us in writing a generic __str__- by simply printing all of the key-values inside of the __dict__

Representational State Transfe (REST) client in python: we saw how to fire a GET HttpRequest from python to a REST web service. then we took the JSON string result and parsed it into a dictionary… and now we can create an object properties from this dictionary (as mentioned above, using __dict__)

More topics covered:

  • REST architecture
  • GET POST PUT DELETE
  • Single Page Application (SPA)
  • python requests install
  • python json import
  • json.loads command
  • list class requires repr implementation 

Links:

09 AUG 2019

Getters and Setters are used  to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.
Class inheritance is the capability of one class to derive or inherit the properties from some another class. The benefits of inheritance are: It represents real-world relationships well. It provides re-usability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it. It is transitive in nature, which means that if class B inherits from another class A, then all the sub-classes of B would automatically inherit from class A
Unified Modeling Language, is a standardized modeling language consisting of an integrated set of diagrams, developed to help system and software developers for specifying, visualizing, constructing, and documenting the artifacts of software system

More topics covered:

  • Data Encapsulation
  • Decorator ( @ )
  • @property – getter
  • @.setter – setter
  • Setter avoid crash using None in __init__ method
  • dir ( class ) – will show all of the properties and functions
  • class <name> ( <class-inherit-from> ) …
  • all classes derive from object
  • override functions
  • Method Resolution Order (MRO) – the order of seeking a method
  • help ( class ) – will print the info of this class and the MRO
  • adding ”’…”’  comment will appear in the help output
  • Polymorpyhism
  • isinstnace, issubclass
  • super ( )
  • <super-class-name>.__init__ (self)
  • __init__ calling super ( )
  • __str_  calling super ( )

Links:

02 AUG 2019

Instance variables data owned by instances of the class. This means that for each object or instance of a class, the instance variables are different. i.e. a Person class could have instance variable of name, age, etc. so each person will have a different name, age…
Magic methods in Python are the special methods which add “magic” to your class. Magic methods are not meant to be invoked directly by you, but the invocation happens internally from the class on a certain action. For example, when you add two numbers using the + operator, internally, the __add__() method will be called.
__str__ and __repr__:  __repr__ is a built-in function used to compute the “official” string reputation of an object, while __str__ is a built-in function that computes the “informal” string representations of an object. So both __repr__ and __str__ are used to represent objects, but in different ways. str( ) is used for creating output for end user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable. For example, if we suspect a float has a small rounding error, repr will show us while str may not. repr( ) compute the “official” string representation of an object (a representation that has all information about the abject) and str() is used to compute the “informal” string representation of an object (a representation that is useful for printing the object). The print ( ) statement and str() built-in function uses __str__ to display the string representation of the object while the repr() built-in function uses __repr__ to display the object.

More topics covered:

  • self.<property> = [value]  will create a member data on self
  • __init__ method should be used to create data members on self
  • __init__ method could accepts arguments for data member values
  • self.__<property> will create a secret data member
  • __repr__ could represent the python code of creating the object
  • _repr__could be manually called by: obj.__repr__( )
  • if __str__ and __repr__ both appear, print will call __str__
  • __str__ and __repr__ both should return a string
  • __eq__ will be called when we write: obj1== obj1
  • class name starts with Capital letter

Links:

26 JULY 2019

*args **kwargs : *args and **kwargs are mostly used in function definitions. *args and **kwargs allow you to pass a variable number of arguments to a function. What does variable mean here is that you do not know before hand that how many arguments can be passed to your function by the user so in this case you use these two keywords. *args is used to send a non-keyworded variable length argument list to the function. **kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function. 

Tuple: A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different comma-separated values. 

oop

Object Oriented Programming (OOP) : Python is an “object-oriented programming language.” Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data, in the form of fields (often known as attributes), and code, in the form of procedures (often known as methods). A feature of objects is an object’s procedures that can access and often modify the data fields of the object with which they are associated (objects have a notion of “this” or “self”). In OOP, computer programs are designed by making them out of objects that interact with one another

More topics covered:

  • *args are send with comma: i.e. foo (1,2,3,4)
  • **kwargs are send by key-value: i.e. foo (coolKey = ‘cool value’)
  • *args are turned into a tuple automatically
  • **kwargs are turned into a dictionary automatically
  • tuple have few methods: index, count, indexing (like list)
  • list could be turned into a tuple, i.e. tuple( [1, 2] )
  • class keyword
  • __init__ method is automatically called when creating a class instance
  • we can define function inside a class
  • iphoneX = IPhone( ) creates an iphoneX object (instance) from class IPhone
  • function defined inside a class are called via the instance

Links: