0% found this document useful (0 votes)
227 views39 pages

1.4.2.python Slides

Built-in class attributes in Python include: - __dict__: A dictionary containing the class's namespace - __doc__: The class documentation string or None if undefined - __name__: The class name - __module__: The module name in which the class is defined Python automatically deletes unneeded objects to free memory space through a process called garbage collection. The garbage collector runs during program execution and is triggered when an object's reference count reaches zero.

Uploaded by

emilronnback
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
227 views39 pages

1.4.2.python Slides

Built-in class attributes in Python include: - __dict__: A dictionary containing the class's namespace - __doc__: The class documentation string or None if undefined - __name__: The class name - __module__: The module name in which the class is defined Python automatically deletes unneeded objects to free memory space through a process called garbage collection. The garbage collector runs during program execution and is triggered when an object's reference count reaches zero.

Uploaded by

emilronnback
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 39

Built-In Class Attributes

• Every Python class keeps following built-in attributes and they


can be accessed using dot (.) operator like any other attribute:
• __dict__ : Dictionary containing the class's namespace.
• __doc__ : Class documentation string or None if undefined.
• __name__: Class name.
• __module__: Module name in which the class is defined.
– This attribute is "__main__" in interactive mode.
• __bases__ : A possibly empty tuple containing the base
classes, in the order of their occurrence in the base class list.
Example
Destroying Objects
(Garbage Collection)
• Python deletes unneeded objects (built-in types or class
instances) automatically to free memory space.
• The process by which Python periodically reclaims blocks of
memory that no longer are in use is termed garbage
collection.
• Python's garbage collector runs during program execution and
is triggered when an object's reference count reaches zero.
– An object's reference count changes as the number of
aliases that point to it changes.
Destroying Objects
• An object's reference count increases when it's assigned a new name or
placed in a container (list, tuple or dictionary).
– The object's reference count decreases when it's deleted with del, its
reference is reassigned, or its reference goes out of scope.
– When an object's reference count reaches zero, Python collects it
automatically.
EXAMPLE
• This __del__() destructor prints the class name of an
instance that is about to be destroyed.
Class Inheritance
• You can create a class by deriving it from a preexisting class by
listing the parent class in parentheses after the new class
name.

• The child class inherits the attributes of its parent class


– you can use those attributes as if they were defined in the
child class.
• A child class can also override data members and methods
from the parent.
EXAMPLE
Multiple Inheritance

• You can use issubclass() or isinstance() functions to check a


relationships of two classes and instances.
• The issubclass(sub, sup) boolean function returns true if the
given subclass sub is indeed a subclass of the superclass sup.
• The isinstance(obj, Class) boolean function returns true
if obj is an instance of class Class or is an instance of a
subclass of Class
Overriding Methods
• You can always override your parent class methods.
Base Overloading Methods
• Following table lists some generic functionality that you can
override in your own classes.
Overloading Operators
• You could define the __add__ method in your class to
perform vector addition and then the plus operator would
behave as per expectation
Data Hiding
• An object's attributes may or may not be visible outside the
class definition.
• For these cases, you can name attributes with a double
underscore prefix, and those attributes will not be directly
visible to outsiders.
Data Hiding
• Python protects those members by internally
changing the name to include the class name.
• You can access such attributes
as object._className__attrName.
• If you would replace your last line as following, then
it would work for you:
Python Modules
• A module allows you to logically organize your
Python code.
• Grouping related code into a module makes the code
easier to understand and use.
• A module is a Python object with arbitrarily named
attributes that you can bind and reference.
• Simply, a module is a file consisting of Python code.
• A module can define functions, classes and variables.
A module can also include runnable code.
The import Statement
• You can use any Python source file as a module by executing
an import statement in some other Python source file.
The import has the following syntax:

• When the interpreter encounters an import statement, it


imports the module if the module is present in the search
path.
• A search path is a list of directories that the interpreter
searches before importing a module.
Example
• To import the module hello.py, you need to put the
following command at the top of the script:
The from...import Statement
• Python's from statement lets you import specific
attributes from a module into the current
namespace.
• The from...import has the following syntax:

• For example, to import the function fibonacci from


the module fib, use the following statement:
The from...import * Statement:
• It is also possible to import all names from a module into the
current namespace by using the following import statement:

Locating Modules:
• When you import a module, the Python interpreter searches
for the module in the following sequences:
– The current directory.
– If the module isn't found, Python then searches each directory in the
shell variable PYTHONPATH.
– If all else fails, Python checks the default path.
• On UNIX, this default path is normally /usr/local/lib/python/.
The PYTHONPATH Variable:
• The PYTHONPATH is an environment variable,
consisting of a list of directories.
• The syntax of PYTHONPATH is the same as that of the
shell variable PATH.
• Here is a typical PYTHONPATH from a Windows
system:
– set PYTHONPATH=c:\python27\lib;
• Here is a typical PYTHONPATH from a UNIX system:
– set PYTHONPATH=/usr/local/lib/python
Namespaces and Scoping
• Variables are names (identifiers) that map to objects.
• A namespace is a dictionary of variable names (keys) and their
corresponding objects (values).
• A Python statement can access variables in a local
namespace and in the global namespace.
– If a local and a global variable have the same name, the local variable
shadows the global variable.
• Each function has its own local namespace.
– Class methods follow the same scoping rule as ordinary functions.
• Python makes educated guesses on whether variables are
local or global.
– It assumes that any variable assigned a value in a function is local.
Namespaces and Scoping
• Therefore, in order to assign a value to a global variable within
a function, you must first use the global statement.
• The statement global VarName tells Python that VarName is a
global variable.
– Python stops searching the local namespace for the variable.
Results
Example

42
The dir( ) Function
• The dir() built-in function returns a sorted list of strings
containing the names defined by a module.
• The list contains the names of all the modules, variables and
functions that are defined in a module.
• Here, the special string variable __name__ is the module's
name, and __file__ is the filename from which the module
was loaded.
The globals() and locals() Functions
• The globals() and locals() functions can be used to return the
names in the global and local namespaces depending on the
location from where they are called.
• If locals() is called from within a function, it will return all the
names that can be accessed locally from that function.
• If globals() is called from within a function, it will return all the
names that can be accessed globally from that function.
• The return type of both these functions is dictionary.
Therefore, names can be extracted using the keys() function.
Packages in Python
• A package is a hierarchical file directory structure that defines
a single Python application environment that consists of
modules and subpackages and sub-subpackages, and so on.
• Consider a file Pots.py available in Phone directory
• We have another two files having different functions with the
same name as above:
– Phone/Isdn.py file having function Isdn()
– Phone/G3.py file having function G3()
• Now, create one more file __init__.py in Phone directory:
– Phone/__init__.py
Packages in Python
• To make all of your functions available when you've imported
Phone, you need to put explicit import statements in
__init__.py as follows:
– from Pots import Pots
– from Isdn import Isdn
– from G3 import G3
Python GUI Programming (Tkinter)
• Python provides various options for developing graphical user
interfaces (GUIs).
• Most important are listed below:
• Tkinter: Tkinter is the Python interface to the Tk GUI toolkit
shipped with Python.
• wxPython: This is an open-source Python interface for
wxWindows http://wxpython.org.
• JPython: JPython is a Python port for Java which gives Python
scripts seamless access to Java class libraries on the local
machine http://www.jython.org.
Tkinter Programming
• Tkinter is the standard GUI library for Python.
• Python when combined with Tkinter provides a fast and easy
way to create GUI applications.
• Tkinter provides a powerful object-oriented interface to the
Tk GUI toolkit.
• All you need to do is perform the following steps:
– Import the Tkinter module.
– Create the GUI application main window.
– Add one or more of the above-mentioned widgets to the GUI
application.
– Enter the main event loop to take action against each event
triggered by the user.
Example
Tkinter
Tkinter Widgets
Standard Attributes
• Let's take a look at how some of their common
attributes, such as sizes, colors and fonts are
specified.
– Dimensions
– Colors
– Fonts
– Anchors
– Relief styles
– Bitmaps
– Cursors
Geometry Management
• All Tkinter widgets have access to specific geometry
management methods, which have the purpose of organizing
widgets throughout the parent widget area.
• Tkinter exposes the following geometry manager classes:
pack, grid, and place.
• The pack() Method - This geometry manager organizes
widgets in blocks before placing them in the parent widget.
• The grid() Method - This geometry manager organizes widgets
in a table-like structure in the parent widget.
• The place() Method -This geometry manager organizes
widgets by placing them in a specific position in the parent
widget.
Example
• Import Tkinter *
• root = Tk()
• frame = Frame(root)
• frame.pack()
• bottomframe = Frame(root)
• bottomframe.pack( side = BOTTOM )
• redbutton = Button(frame, text="Red", fg="red")
redbutton.pack( side = LEFT)
• greenbutton = Button(frame, text="Brown", fg="brown")
greenbutton.pack( side = LEFT )
Example
• bluebutton = Button(frame, text="Blue", fg="blue")
• bluebutton.pack( side = LEFT )
• blackbutton = Button(bottomframe, text="Black", fg="black")
• blackbutton.pack( side = BOTTOM) root.mainloop()
Example
• Import Tkinter
• class GUIDemo(Frame): # (inherit) Tkinter Frame
• def __init__(self, master=None):
• Frame.__init__(self, master)
• self.grid()
• self.createWidgets()

• def createWidgets(self):
• self.inputText = Label(self)
• self.inputText["text"] = "Input:"
• self.inputText.grid(row=0, column=0)
• self.inputField = Entry(self)
• self.inputField["width"] = 50
• self.inputField.grid(row=0, column=1, columnspan=6)

• self.outputText = Label(self)
• self.outputText["text"] = "Output:"
• self.outputText.grid(row=1, column=0)
• self.outputField = Entry(self)
• self.outputField["width"] = 50
• self.outputField.grid(row=1, column=1, columnspan=6)
• self.new = Button(self)
• self.new["text"] = "New"
• self.new.grid(row=2, column=0)
• self.load = Button(self)
• self.load["text"] = "Load"
• self.load.grid(row=2, column=1)
• self.save = Button(self)
• self.save["text"] = "Save"
• self.save.grid(row=2, column=2)
• self.encode = Button(self)
• self.encode["text"] = "Encode"
• self.encode.grid(row=2, column=3)
• self.decode = Button(self)
• self.decode["text"] = "Decode"
• self.decode.grid(row=2, column=4)
• self.clear = Button(self)
• self.clear["text"] = "Clear"
• self.clear.grid(row=2, column=5)
• self.copy = Button(self)
• self.copy["text"] = "Copy"
• self.copy.grid(row=2, column=6)
• self.displayText = Label(self)
• self.displayText["text"] = "something happened"
• self.displayText.grid(row=3, column=0, columnspan=7)

• if __name__ == '__main__':
• root = Tk()
• app = GUIDemo(master=root)
• app.mainloop()

You might also like