Here is a Python class with the specifications provided in the question:
class PICTURE:
def __init__(self, pno, category, location):
self.pno = pno
self.category = category
self.location = location
def FixLocation(self, new_location):
self.location = new_location
This defines a PICTURE class with three instance attributes - pno, category and location as specified in the question. It also defines a FixLocation method to assign a new location as required.
Object Oriented Programming, Networking, and Linux/Unix commands were discussed. Key points included: defining classes and instantiating objects in Python, class variables and methods, inheritance and method overriding, networking terminology like DNS and VPN, common Linux shell commands like ls, cd, grep, and piping commands together. Networking concepts like LAN, MAN, WAN and the basic communication flow of requests and responses were also covered.
C++ is an object-oriented programming language that is an incremented version of C with classes added. Some key differences between C and C++ are that C++ uses object-oriented programming with classes that can contain both data and functions, while C focuses more on procedures/functions and allows any function to access data. The document then discusses the basic concepts of object-oriented programming in C++ including classes, objects, polymorphism, inheritance, encapsulation, and data abstraction. It provides examples of classes, objects, reference variables, default arguments, and dynamic memory allocation in C++.
- Namespaces map names to objects and are implemented as dictionaries in Python. Examples include built-in names, global module names, and local function names.
- There is no relation between names in different namespaces. A name prefixed with a module name refers to an attribute of that module.
- Namespaces are created at different times - built-in names exist at interpreter start, module namespaces when the module is read in, and local function namespaces when a function is called.
Python namespaces provide a way to organize and access variables and functions. There are two types of namespaces: local and global. A local namespace contains names defined within a function, while a global namespace contains names defined outside of functions and is accessible throughout a program. Understanding namespaces and scopes is important for avoiding naming conflicts and ensuring code runs smoothly. Best practices include avoiding global variables when possible and using descriptive naming conventions.
The document summarizes a presentation on the Python programming language. It includes sections on introducing Python, operators and data types, conditions and loops, functions and exception handling, classes and inheritance, Python libraries, a sample library management project in Python, and queries. The presentation covers key Python concepts like data types, operators, conditional statements, loops, functions, object-oriented programming concepts like classes and inheritance, and popular Python libraries like NumPy and Pandas. It also includes code for a library management project built in Python.
Functions allow programmers to organize and reuse code. Defining a function involves using the def keyword followed by the function name and parameters. Functions create a new local scope, and variables are searched in local, then global, then built-in scopes. Arguments passed to functions are assigned to parameter variables in the local scope. Functions can return values, and mutable objects like lists can be modified in-place by functions. Python also supports anonymous lambda functions defined with a single expression.
Python supports object-oriented programming through classes, objects, and related concepts like inheritance, polymorphism, and encapsulation. A class acts as a blueprint to create object instances. Objects contain data fields and methods. Inheritance allows classes to inherit attributes and behaviors from parent classes. Polymorphism enables the same interface to work with objects of different types. Encapsulation helps protect data by restricting access.
Object-oriented programming (OOP) organizes code around data objects rather than functions. In Python, classes are user-defined templates for objects that contain attributes (data) and methods (functions). When a class is instantiated, an object is created with its own copies of the attributes. Self refers to the object itself and allows methods to access and modify its attributes. Classes in Python allow for code reusability, modularity, and flexibility through encapsulation, inheritance, and polymorphism.
The document discusses Python objects and types. It covers key concepts like object-oriented programming in Python, classes and instances, namespaces, scoping, and exception handling. Some main points include:
- Everything in Python is an object with an identity, type, and value. Objects live in dynamic namespaces and can be accessed via names.
- Classes are type objects that act as templates for creating instances when called. Instances are objects with the same methods and attributes as its class.
- Namespaces are where names are mapped to objects. Python has module, class, and instance namespaces that follow LEGB scoping rules.
- Exceptions are class objects that inherit from the built-in Exception class. The raise statement is used
This document discusses objects and classes in Java. It begins by defining what a class is - a template that defines common properties of objects. Everything in a Java program must be encapsulated within a class. A class defines an object's state via fields and behavior via methods. The document then discusses how to define classes by specifying fields, methods, and constructors. It provides examples of creating objects from classes and accessing object members. The document also covers key object-oriented programming concepts like encapsulation and inheritance.
ITS-16163: Module 7 Introduction to Object-Oriented Programming Basicsoudesign
This document provides an introduction to object-oriented programming (OOP) in Python. It discusses key OOP concepts like classes, objects, attributes, and methods. Classes act as blueprints that define the attributes and behaviors of objects. Objects are instantiated from classes. The document uses examples like an Employee class to demonstrate how to define classes with initialization methods and instance methods, and how to create multiple object instances from a single class. It also provides example code of a critter caretaker program to demonstrate OOP in practice.
The document provides an introduction to object-oriented programming concepts in Python using PyTorch examples. It discusses key object-oriented programming concepts like classes, instances, attributes, encapsulation, inheritance and polymorphism. It also summarizes some example PyTorch code to demonstrate concepts like classes, methods, inheritance and polymorphism in an object-oriented deep learning context.
The document discusses key concepts of object-oriented programming (OOP) including objects, classes, constructors, encapsulation, inheritance, and polymorphism. It provides examples to illustrate each concept. Objects contain data (states) and behaviors (methods). A class acts as a blueprint to create objects. Constructors initialize objects. Encapsulation hides implementation details and controls access via getters and setters. Inheritance allows classes to acquire properties and behaviors of other classes. Polymorphism allows the same method to process objects differently based on their data type.
The document discusses different programming paradigms including procedural, object-oriented, functional, and declarative. The procedural paradigm uses procedures to manipulate passive data objects. The object-oriented paradigm deals with active objects that contain methods to perform actions. Functional programming treats programs as mathematical functions that map inputs to outputs. Declarative programming uses logical reasoning from facts and rules to deduce new facts in response to queries.
These questions will be a bit advanced level 2sadhana312471
These questions will be a bit advanced(Intermediate) in terms of Python interview.
This is the continuity of Nail the Python Interview Questions.
The fields that these questions will help you in are:
• Python Developer
• Data Analyst
• Research Analyst
• Data Scientist
This PPT File helps IT freshers with the Basic Interview Questions, which will boost there confidence before going to the Interview. For more details and Interview Questions please log in www.rekruitin.com and click on Job Seeker tools. Also register on the and get employed.
By ReKruiTIn.com
Functions allow programmers to organize and reuse code. Defining a function involves using the def keyword followed by the function name and parameters. Functions create a new local scope, and variables are searched in local, then global, then built-in scopes. Arguments passed to functions are assigned to parameter variables in the local scope. Functions can return values, and mutable objects like lists can be modified in-place by functions. Python also supports anonymous lambda functions defined with a single expression.
Python supports object-oriented programming through classes, objects, and related concepts like inheritance, polymorphism, and encapsulation. A class acts as a blueprint to create object instances. Objects contain data fields and methods. Inheritance allows classes to inherit attributes and behaviors from parent classes. Polymorphism enables the same interface to work with objects of different types. Encapsulation helps protect data by restricting access.
Object-oriented programming (OOP) organizes code around data objects rather than functions. In Python, classes are user-defined templates for objects that contain attributes (data) and methods (functions). When a class is instantiated, an object is created with its own copies of the attributes. Self refers to the object itself and allows methods to access and modify its attributes. Classes in Python allow for code reusability, modularity, and flexibility through encapsulation, inheritance, and polymorphism.
The document discusses Python objects and types. It covers key concepts like object-oriented programming in Python, classes and instances, namespaces, scoping, and exception handling. Some main points include:
- Everything in Python is an object with an identity, type, and value. Objects live in dynamic namespaces and can be accessed via names.
- Classes are type objects that act as templates for creating instances when called. Instances are objects with the same methods and attributes as its class.
- Namespaces are where names are mapped to objects. Python has module, class, and instance namespaces that follow LEGB scoping rules.
- Exceptions are class objects that inherit from the built-in Exception class. The raise statement is used
This document discusses objects and classes in Java. It begins by defining what a class is - a template that defines common properties of objects. Everything in a Java program must be encapsulated within a class. A class defines an object's state via fields and behavior via methods. The document then discusses how to define classes by specifying fields, methods, and constructors. It provides examples of creating objects from classes and accessing object members. The document also covers key object-oriented programming concepts like encapsulation and inheritance.
ITS-16163: Module 7 Introduction to Object-Oriented Programming Basicsoudesign
This document provides an introduction to object-oriented programming (OOP) in Python. It discusses key OOP concepts like classes, objects, attributes, and methods. Classes act as blueprints that define the attributes and behaviors of objects. Objects are instantiated from classes. The document uses examples like an Employee class to demonstrate how to define classes with initialization methods and instance methods, and how to create multiple object instances from a single class. It also provides example code of a critter caretaker program to demonstrate OOP in practice.
The document provides an introduction to object-oriented programming concepts in Python using PyTorch examples. It discusses key object-oriented programming concepts like classes, instances, attributes, encapsulation, inheritance and polymorphism. It also summarizes some example PyTorch code to demonstrate concepts like classes, methods, inheritance and polymorphism in an object-oriented deep learning context.
The document discusses key concepts of object-oriented programming (OOP) including objects, classes, constructors, encapsulation, inheritance, and polymorphism. It provides examples to illustrate each concept. Objects contain data (states) and behaviors (methods). A class acts as a blueprint to create objects. Constructors initialize objects. Encapsulation hides implementation details and controls access via getters and setters. Inheritance allows classes to acquire properties and behaviors of other classes. Polymorphism allows the same method to process objects differently based on their data type.
The document discusses different programming paradigms including procedural, object-oriented, functional, and declarative. The procedural paradigm uses procedures to manipulate passive data objects. The object-oriented paradigm deals with active objects that contain methods to perform actions. Functional programming treats programs as mathematical functions that map inputs to outputs. Declarative programming uses logical reasoning from facts and rules to deduce new facts in response to queries.
These questions will be a bit advanced level 2sadhana312471
These questions will be a bit advanced(Intermediate) in terms of Python interview.
This is the continuity of Nail the Python Interview Questions.
The fields that these questions will help you in are:
• Python Developer
• Data Analyst
• Research Analyst
• Data Scientist
This PPT File helps IT freshers with the Basic Interview Questions, which will boost there confidence before going to the Interview. For more details and Interview Questions please log in www.rekruitin.com and click on Job Seeker tools. Also register on the and get employed.
By ReKruiTIn.com
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyYannis
The doctoral thesis trajectory has been often characterized as a “long and windy road” or a journey to “Ithaka”, suggesting the promises and challenges of this journey of initiation to research. The doctoral candidates need to complete such journey (i) preserving and even enhancing their wellbeing, (ii) overcoming the many challenges through resilience, while keeping (iii) high standards of ethics and (iv) scientific rigor. This talk will provide a personal account of lessons learnt and recommendations from a senior researcher over his 30+ years of doctoral supervision and care for doctoral students. Specific attention will be paid on the special features of the (i) interdisciplinary doctoral research that involves Information and Communications Technologies (ICT) and other scientific traditions, and (ii) the challenges faced in the complex technological and research landscape dominated by Artificial Intelligence.
David Boutry - Mentors Junior DevelopersDavid Boutry
David Boutry is a Senior Software Engineer in New York with expertise in high-performance data processing and cloud technologies like AWS and Kubernetes. With over eight years in the field, he has led projects that improved system scalability and reduced processing times by 40%. He actively mentors aspiring developers and holds certifications in AWS, Scrum, and Azure.
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...ijfcstjournal
One of the major challenges for software, nowadays, is software cost estimation. It refers to estimating the
cost of all activities including software development, design, supervision, maintenance and so on. Accurate
cost-estimation of software projects optimizes the internal and external processes, staff works, efforts and
the overheads to be coordinated with one another. In the management software projects, estimation must
be taken into account so that reduces costs, timing and possible risks to avoid project failure. In this paper,
a decision- support system using a combination of multi-layer artificial neural network and decision tree is
proposed to estimate the cost of software projects. In the model included into the proposed system,
normalizing factors, which is vital in evaluating efforts and costs estimation, is carried out using C4.5
decision tree. Moreover, testing and training factors are done by multi-layer artificial neural network and
the most optimal values are allocated to them. The experimental results and evaluations on Dataset
NASA60 show that the proposed system has less amount of the total average relative error compared with
COCOMO model.
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSsamueljackson3773
In this paper, the author discusses the concerns of using various wireless communications and how to use
them safely. The author also discusses the future of the wireless industry, wireless communication
security, protection methods, and techniques that could help organizations establish a secure wireless
connection with their employees. The author also discusses other essential factors to learn and note when
manufacturing, selling, or using wireless networks and wireless communication systems.
A substation at an airport is a vital infrastructure component that ensures reliable and efficient power distribution for all airport operations. It acts as a crucial link, converting high-voltage electricity from the main grid to the lower voltages needed for various airport facilities. This essay will explore the functions, components, and importance of a substation at an airport.
Functions of an Airport Substation:
Voltage Conversion:
Substations step down high-voltage electricity to lower levels suitable for airport operations, like terminal buildings, runways, and other facilities.
Power Distribution:
They distribute electricity to various loads, including lighting, air conditioning, navigation systems, and ground support equipment.
Grid Stability:
Substations help maintain the stability of the power grid by controlling voltage levels and managing power flows.
Redundancy and Reliability:
Airports often have redundant substations or interconnected systems to ensure uninterrupted power supply, even in case of a fault.
Switching and Control:
Substations provide switching capabilities to connect or disconnect circuits, enabling maintenance and power management.
Protection:
Substations incorporate protective devices, like circuit breakers and relays, to safeguard the power system from faults and ensure safe operation.
Key Components of an Airport Substation:
Transformers: These convert high-voltage electricity to lower voltage levels.
Circuit Breakers: These devices switch circuits on or off, protecting the system from faults.
Busbars: These are large, conductive bars that distribute electricity from transformers to other equipment.
Switchgear: This includes equipment that controls the flow of electricity, such as isolators and switches.
Control and Protection Systems: These systems monitor the substation's performance, detect faults, and automatically initiate corrective actions.
Capacitors: These improve the power factor and reduce losses in the system.
Importance of Airport Substations:
Reliable Power Supply:
Substations are essential for providing reliable power to critical airport functions, ensuring safety and efficiency.
Safe and Efficient Operations:
They contribute to the safe and efficient operation of runways, terminals, and other airport facilities.
Airport Infrastructure:
Substations are an integral part of the airport's infrastructure, enabling various operations and services.
Economic Impact:
Substations support the economic activities of the airport, including passenger and cargo handling.
Modernization and Sustainability:
Modern substations incorporate advanced technologies and systems to improve efficiency, reduce energy consumption, and enhance sustainability.
In conclusion, an airport substation is a crucial component of airport infrastructure, ensuring reliable and efficient power distribution, grid stability, and safe operations.
Third Review PPT that consists of the project d etails like abstract.Sowndarya6
CyberShieldX is an AI-driven cybersecurity SaaS web application designed to provide automated security analysis and proactive threat mitigation for business websites. As cyber threats continue to evolve, traditional security tools like OpenVAS and Nessus require manual configurations and lack real-time automation. CyberShieldX addresses these limitations by integrating AI-powered vulnerability assessment, intrusion detection, and security maintenance services. Users can analyze their websites by simply submitting a URL, after which CyberShieldX conducts an in-depth vulnerability scan using advanced security tools such as OpenVAS, Nessus, and Metasploit. The system then generates a detailed report highlighting security risks, potential exploits, and recommended fixes. Premium users receive continuous security monitoring, automatic patching, and expert assistance to fortify their digital infrastructure against emerging threats. Built on a robust cloud infrastructure using AWS, Docker, and Kubernetes, CyberShieldX ensures scalability, high availability, and efficient security enforcement. Its AI-driven approach enhances detection accuracy, minimizes false positives, and provides real-time security insights. This project will cover the system's architecture, implementation, and its advantages over existing security solutions, demonstrating how CyberShieldX revolutionizes cybersecurity by offering businesses a smarter, automated, and proactive defense mechanism against ever-evolving cyber threats.
This study will provide the audience with an understanding of the capabilities of soft tools such as Artificial Neural Networks (ANN), Support Vector Regression (SVR), Model Trees (MT), and Multi-Gene Genetic Programming (MGGP) as a statistical downscaling tool. Many projects are underway around the world to downscale the data from Global Climate Models (GCM). The majority of the statistical tools have a lengthy downscaling pipeline to follow. To improve its accuracy, the GCM data is re-gridded according to the grid points of the observed data, standardized, and, sometimes, bias-removal is required. The current work suggests that future precipitation can be predicted by using precipitation data from the nearest four grid points as input to soft tools and observed precipitation as output. This research aims to estimate precipitation trends in the near future (2021-2050), using 5 GCMs, for Pune, in the state of Maharashtra, India. The findings indicate that each one of the soft tools can model the precipitation with excellent accuracy as compared to the traditional method of Distribution Based Scaling (DBS). The results show that ANN models appear to give the best results, followed by MT, then MGGP, and finally SVR. This work is one of a kind in that it provides insights into the changing monsoon season in Pune. The anticipated average precipitation levels depict a rise of 300–500% in January, along with increases of 200-300% in February and March, and a 100-150% increase for April and December. In contrast, rainfall appears to be decreasing by 20-30% between June and September.
This presentation highlights project development using software development life cycle (SDLC) with a major focus on incorporating research in the design phase to develop innovative solution. Some case-studies are also highlighted which makes the reader to understand the different phases with practical examples.
How Binning Affects LED Performance & Consistency.pdfMina Anis
🔍 What’s Inside:
📦 What Is LED Binning?
• The process of sorting LEDs by color temperature, brightness, voltage, and CRI
• Ensures visual and performance consistency across large installations
🎨 Why It Matters:
• Inconsistent binning leads to uneven color and brightness
• Impacts brand perception, customer satisfaction, and warranty claims
📊 Key Concepts Explained:
• SDCM (Standard Deviation of Color Matching)
• Recommended bin tolerances by application (e.g., 1–3 SDCM for retail/museums)
• How to read bin codes from LED datasheets
• The difference between ANSI/NEMA standards and proprietary bin maps
🧠 Advanced Practices:
• AI-assisted bin prediction
• Color blending and dynamic calibration
• Customized binning for high-end or global projects
How Binning Affects LED Performance & Consistency.pdfMina Anis
Ad
Basics of Programming_Python__Lecture__3.ppt
1. ASC, National Centre for Physics
Programming Python – Lecture#3
Mr. Adeel-ur-Rehman
2. Programming Python
ASC, National Centre for Physics
Scheme of Lecture
Object-Oriented Framework
Python Scopes and Namespaces
The self argument
The __init__ method
Classes
The __getitem__ and __setitem__ methods
Inheritance and Multiple Inheritance
Iterators and Generators
Exception Handling
Gui Tkinter Programming Basics
3. Programming Python
ASC, National Centre for Physics
Object-Oriented Framework
Two basic programming paradigms:
Procedural
Organizing programs around functions or
blocks of statements which manipulate data.
Object-Oriented
combining data and functionality and wrap it
inside what is called an object.
4. Programming Python
ASC, National Centre for Physics
Object-Oriented Framework
Classes and objects are the two main aspects
of object oriented programming.
A class creates a new type.
Where objects are instances of the class.
An analogy is that we can have variables of
type int which translates to saying that
variables that store integers are variables
which are instances (objects) of the int class.
5. Programming Python
ASC, National Centre for Physics
Object-Oriented Framework
Objects can store data using ordinary
variables that belong to the object.
Variables that belong to an object or class are
called as fields.
Objects can also have functionality by using
functions that belong to the class. Such
functions are called methods.
This terminology is important because it helps
us to differentiate between a function which
is separate by itself and a method which
belongs to an object.
6. Programming Python
ASC, National Centre for Physics
Object-Oriented Framework
Remember, that fields are of two types
they can belong to each instance (object) of the
class
or they belong to the class itself.
They are called instance variables and class
variables respectively.
A class is created using the class keyword.
The fields and methods of the class are listed
in an indented block.
7. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
A namespace is a mapping from names to
objects.
Most namespaces are currently implemented
as Python dictionaries, but that’s normally not
noticeable in any way.
Examples of namespaces are:
the set of built-in names (functions such as abs(),
and built-in exception names)
the global names in a module;
and the local names in a function invocation.
8. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
In a sense the set of attributes of an object also
form a namespace.
The important thing to know about
namespaces is that there is absolutely no
relation between names in different
namespaces;
for instance, two different modules may both
define a function “maximize” without confusion —
users of the modules must prefix it with the
module name.
9. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
In the expression modname.funcname,
modname is a module object and
funcname is an attribute of it.
In this case there happens to be a
straightforward mapping between the
module’s attributes and the global
names defined in the module:
they share the same namespace!
10. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
Namespaces are created at different
moments and have different lifetimes.
The namespace containing the built-in names
is created when the Python interpreter starts
up, and is never deleted.
The global namespace for a module is
created when the module definition is read
in;
normally, module namespaces also last until the
interpreter quits.
11. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
The statements executed by the top-
level invocation of the interpreter, either
read from a script file or interactively,
are considered part of a module called
__main__,
so they have their own global namespace.
The built-in names actually also live in a
module;
this is called __builtin__.
12. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
The local namespace for a function is
created
when the function is called
And deleted
when the function returns or raises an
exception that is not handled within the
function.
Of course, recursive invocations each have
their own local namespace.
13. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
A scope is a textual region of a Python
program where a namespace is directly
accessible.
“Directly accessible” here means that an
unqualified reference to a name
attempts to find the name in the
namespace.
14. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
Although scopes are determined
statically, they are used dynamically.
At any time during execution, there are
at least three nested scopes whose
namespaces are directly accessible:
the innermost scope, which is searched
first, contains the local names; the
namespaces of any enclosing functions,
15. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
which are searched starting with the
nearest enclosing scope; the middle scope,
searched next, contains the current
module’s global names;
and the outermost scope (searched last) is
the namespace containing built-in names.
16. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
If a name is declared global, then all
references and assignments go directly
to the middle scope containing the
module’s global names.
Otherwise, all variables found outside of
the innermost scope are read-only.
17. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
Usually, the local scope references the
local names of the current function.
Outside of functions, the local scope
references the same namespace as the
global scope:
the module’s namespace.
Class definitions place yet another
namespace in the local scope.
18. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
A special quirk of Python is that
assignments always go into the
innermost scope.
Assignments do not copy data—
they just bind names to objects.
The same is true for deletions:
the statement ‘del x’ removes the binding
of x from the namespace referenced by the
local scope.
19. Programming Python
ASC, National Centre for Physics
Python Scopes and Namespaces
In fact, all operations that introduce
new names use the local scope:
in particular, import statements and
function definitions bind the module or
function name in the local scope. (The
global statement can be used to indicate
that particular variables live in the global
scope.)
20. Programming Python
ASC, National Centre for Physics
The self
Class methods have only one specific
difference from ordinary functions
they have an extra variable that has to be added
to the beginning of the parameter list
but we do not give a value for this parameter
when we call the method.
this particular variable refers to the object itself,
and by convention, it is given the name self.
21. Programming Python
ASC, National Centre for Physics
The self
Although, we can give any name for this
parameter, it is strongly recommended that
we use the name self.
Any other name is definitely frowned upon.
There are many advantages to using a
standard name
any reader of our program will immediately
recognize that it is the object variable i.e. the self
and even specialized IDEs (Integrated
Development Environments such as Boa
Constructor) can help us if we use this particular
name.
22. Programming Python
ASC, National Centre for Physics
The self
Python will automatically provide this value in
the function parameter list.
For example, if we have a class called
MyClass and an instance (object) of this
class called MyObject, then when we call a
method of this object as
MyObject.method(arg1, arg2), this is
automatically converted to
MyClass.method(MyObject, arg1, arg2).
This is what the special self is all about.
23. Programming Python
ASC, National Centre for Physics
The __init__ method
__init__ is called immediately after an
instance of the class is created.
It would be tempting but incorrect to call this
the constructor of the class.
Tempting, because it looks like a constructor (by
convention, __init__ is the first method defined for
the class), acts like one (it's the first piece of code
executed in a newly created instance of the class),
and even sounds like one ("init" certainly suggests
a constructor-ish nature).
24. Programming Python
ASC, National Centre for Physics
The __init__ method
Incorrect, because the object has already
been constructed by the time __init__ is
called, and we already have a valid
reference to the new instance of the class.
But __init__ is the closest thing we're
going to get in Python to a constructor,
and it fills much the same role.
25. Programming Python
ASC, National Centre for Physics
Creating a Class
class Person:
pass # A new block
p = Person()
print p
#<__main__.Person instance at 0x816a6cc>
26. Programming Python
ASC, National Centre for Physics
Object Methods
class Person:
def sayHi(self):
print 'Hello, how are you?'
p = Person()
p.sayHi()
# This short example can also be
#written as Person().sayHi()
27. Programming Python
ASC, National Centre for Physics
Class and Object Variables
class Person:
'''Represents a person.'''
population = 0
def __init__(self, name):
'''Initializes the person.'''
self.name = name
print '(Initializing %s)' % self.name
# When this person is created, # he/she adds to the population
Person.population += 1
def sayHi(self):
'''Greets the other person. Really, that's all it does.'''
print 'Hi, my name is %s.' % self.name
28. Programming Python
ASC, National Centre for Physics
Class and Object Variables
def howMany(self):
'''Prints the current population.''‘
# There will always be at least one person
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %s persons here.' % Person.population
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
29. Programming Python
ASC, National Centre for Physics
Special Class Methods
In addition to normal class methods, there
are a number of special methods which
Python classes can define.
Instead of being called directly by our code
(like normal methods), special methods are
called for you by Python in particular
circumstances or when specific syntax is
used.
We can get and set items with a syntax that
doesn't include explicitly invoking methods.
30. Programming Python
ASC, National Centre for Physics
The __getitem__ Special Method
def __getitem__(self, key): return self.data[key]
>>> f
{'name':'/music/_singles/kairo.mp3'}
>>> f.__getitem__("name")
'/music/_singles/kairo.mp3'
>>> f["name"] (2)
'/music/_singles/kairo.mp3'
The __getitem__ special method looks simple
enough. Like the normal methods clear, keys,
and values, it just redirects to the dictionary to
return its value. But how does it get called?
31. Programming Python
ASC, National Centre for Physics
The __getitem__ Special Method
Well, we can call __getitem__ directly, but in practice
we wouldn't actually do that;
The right way to use __getitem__ is to get Python to
call it for us.
This looks just like the syntax we would use to get a
dictionary value, and in fact it returns the value we
would expect.
But here's the missing link: under the covers, Python
has converted this syntax to the method call:
f.__getitem__("name").
That's why __getitem__ is a special class method;
not only can we call it ourself, we can get Python to
call it for us by using the right syntax.
32. Programming Python
ASC, National Centre for Physics
The __setitem__ Special Method
def __setitem__(self, key, item):self.data[key] = item
>>> f
{'name':'/music/_singles/kairo.mp3'}
>>> f.__setitem__("genre", 31)
>>> f
{'name':'/music/_singles/kairo.mp3', 'genre':31}
>>> f["genre"] = 32
>>> f
{'name':'/music/_singles/kairo.mp3', 'genre':32}
33. Programming Python
ASC, National Centre for Physics
The __setitem__ Special Method
Like the __getitem__ method, __setitem__ simply
redirects to the real dictionary self.data to do its work.
And like __getitem__, we wouldn't ordinarily call it
directly like this.
Python calls __setitem__ for us when we use the right
syntax.
This looks like regular dictionary syntax, except of
course that f is really a class that's trying very hard to
masquerade as a dictionary, and __setitem__ is an
essential part of that masquerade.
This second last line of code actually calls
f.__setitem__("genre", 32) under the covers.
34. Programming Python
ASC, National Centre for Physics
Inheritance
One of the major benefits of object
oriented programming is reuse of code
One of the ways this is achieved is
through the inheritance mechanism.
Inheritance can be best imagined as
implementing a type and subtype
relationship between classes.
Consider this example:
35. Programming Python
ASC, National Centre for Physics
Using Inheritance
class SchoolMember:
'''Represents any school member.'''
def __init__(self, name, age):
self.name = name
self.age = age
print '(Initialized SchoolMember: %s)' %
self.name
def tell(self):
print 'Name:"%s" Age:"%s" ' % (self.name,
self.age),
36. Programming Python
ASC, National Centre for Physics
Using Inheritance
class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print '(Initialized Teacher: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Salary:"%d"' % self.salary
37. Programming Python
ASC, National Centre for Physics
Using Inheritance
class Student(SchoolMember):
'''Represents a student.'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print '(Initialized Student: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Marks:"%d"' % self.marks
38. Programming Python
ASC, National Centre for Physics
Using Inheritance
t = Teacher('Mrs. Abraham', 40, 30000)
s = Student('Swaroop', 21, 75)
print # prints a blank line
members = [t, s]
for member in members:
member.tell() # Works for instances of
Student as well as Teacher
39. Programming Python
ASC, National Centre for Physics
Multiple Inheritance
Python supports a limited form of multiple
inheritance as well.
A class definition with multiple base classes
looks as follows:
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
<statement-N>
The only rule necessary to explain the
semantics is the resolution rule used for class
attribute references.
40. Programming Python
ASC, National Centre for Physics
Multiple Inheritance
This is depth-first, left-to-right. Thus, if an attribute is
not found in DerivedClassName, it is searched in
Base1, then (recursively) in the base classes of
Base1, and only if it is not found there, it is searched
in Base2, and so on.
A well-known problem with multiple inheritance is a
class derived from two classes that happen to have a
common base class. While it is easy enough to figure
out what happens in this case (the instance will have
a single copy of “instance variables” or data
attributes used by the common base class).
41. Programming Python
ASC, National Centre for Physics
Iterators
By now, you’ve probably noticed that
most container objects can looped over
using a for statement:
for element in [1, 2, 3]:
print element
for element in (1, 2, 3):
print element
for key in {’one’:1, ’two’:2}:
print key
42. Programming Python
ASC, National Centre for Physics
Iterators
for char in "123":
print char
for line in open("myfile.txt"):
print line
This style of access is clear, concise, and convenient.
The use of iterators pervades and unifies Python.
Behind the scenes, the for statement calls iter() on
the container object.
The function returns an iterator object that defines
the method next() which accesses elements in the
container one at a time.
When there are no more elements, next() raises a
StopIteration exception which tells the for loop to
terminate.
This example shows how it all works:
43. Programming Python
ASC, National Centre for Physics
Iterators
>>> s = ’abc’
>>> it = iter(s)
>>> it
<iterator object at 0x00A1DB50>
>>> it.next()
’a’
>>> it.next()
’b’
44. Programming Python
ASC, National Centre for Physics
Iterators
>>> it.next()
’c’
>>> it.next()
Traceback (most recent call last):
File "<pyshell#6>", line 1, in -toplevel
it.next()
StopIteration
45. Programming Python
ASC, National Centre for Physics
Iterators
Having seen the mechanics behind the
iterator protocol, it is easy to add
iterator behavior to our classes.
Define a __iter__() method which
returns an object with a next() method.
If the class defines next(), then
__iter__() can just return self:
46. Programming Python
ASC, National Centre for Physics
Iterators
>>> class Reverse:
"Iterator for looping over a sequence
backwards"
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
47. Programming Python
ASC, National Centre for Physics
Iterators
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
49. Programming Python
ASC, National Centre for Physics
Generators
Generators are a simple and powerful tool for
creating iterators.
They are written like regular functions but
use the yield statement whenever they want
to return data.
Each time the next() is called, the generator
resumes where it left-off (it remembers all
the data values and which statement was last
executed).
An example shows that generators can be
trivially easy to create:
50. Programming Python
ASC, National Centre for Physics
Generators
>>> def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
>>> for char in reverse(’golf’):
print char
f
l
o
g
51. Programming Python
ASC, National Centre for Physics
Generators
Anything that can be done with generators can also
be done with class based iterators as described in the
previous section.
What makes generators so compact is that the
__iter__() and next() methods are created
automatically.
Another key feature is that the local variables and
execution state are automatically saved between
calls.
This made the function easier to write and much
more clear than an approach using class variables
like self.index and self.data.
52. Programming Python
ASC, National Centre for Physics
Generators
In addition to automatic method
creation and saving program state,
when generators terminate, they
automatically raise StopIteration.
In combination, these features make it
easy to create iterators with no more
effort than writing a regular function.
53. Programming Python
ASC, National Centre for Physics
Exception Handling
Exceptions occur when certain exceptional
situations occur in our program.
For example, what if we are reading a file and
we accidentally deleted it in another window
or some other error occurred? Such situations
are handled using exceptions.
What if our program had some invalid
statements?
This is handled by Python which raises its
hands and tells you there is an error.
54. Programming Python
ASC, National Centre for Physics
Exception Handling
Consider a simple print statement.
What if we misspelt print as Print?
Note the capitalization.
In this case, Python raises a syntax error.
>>> Print 'Hello, World' File "<stdin>", line 1 Print
'Hello, World' ^ SyntaxError: invalid syntax
>>> print 'Hello, World'
Hello, World
>>>
Observe that a SyntaxError is raised and also the
location where the error was detected, is printed.
This is what a handler for the error does.
55. Programming Python
ASC, National Centre for Physics
Exception Handling
To show the usage of exceptions, we will try to read
input from the user and see what happens.
>>> s = raw_input('Enter something --> ')
Enter something --> Traceback (most recent call
last): File "<stdin>", line 1, in ? EOFError
>>>
Here, we ask the user for input and if he/she presses
Ctrl-d i.e. the EOF (end of file) character, then
Python raises an error called EOFError.
Next, we will see how to handle such errors.
56. Programming Python
ASC, National Centre for Physics
Exception Handling
We can handle exceptions using the
try..except statement.
We basically put our usual statements
within the try-block.
And we put all the error handlers in the
except-block.
57. Programming Python
ASC, National Centre for Physics
Exception Handling
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print 'nWhy did you do an EOF on me?' sys.exit() #
Exit the program
except:
print 'nSome error/exception occurred.'
# Here, we are not exiting the program
print 'Done'
58. Programming Python
ASC, National Centre for Physics
Exception Handling
We put all the statements that might raise an error in
the try block
And then handle all errors and exceptions in the
except clause/block.
The except clause can handle a single specified error
or exception or a parenthesized list of
errors/exceptions.
If no names of errors or exceptions are supplied, it
will handle all errors and exceptions. There has to be
at least one except clause associated with every try
clause.
59. Programming Python
ASC, National Centre for Physics
Exception Handling
If any error or exception is not handled,
then the default Python handler is
called which stops the execution of the
program and prints a message.
We can also have an else clause with
the try..catch block.
The else clause is executed if no
exception occurs.
60. Programming Python
ASC, National Centre for Physics
Exception Handling
We can also get the exception object
so that we can retrieve additional
information about the exception which
has occurred.
This is demonstrated in the next
example.
61. Programming Python
ASC, National Centre for Physics
Exception Handling
We can raise exceptions using the raise
statement
- we specify the name of the
error/exception and the exception object.
The error or exception that we can raise
should be a class which directly or
indirectly is a derived class of the Error or
Exception class respectively.
62. Programming Python
ASC, National Centre for Physics
Exception Handling
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3)
63. Programming Python
ASC, National Centre for Physics
Exception Handling
Other work can go as usual here.
except EOFError:
print 'nWhy did you do an EOF on me?‘
except ShortInputException, x:
print ‘ nThe input was of length %d, it
should be at least %d' % (x.length,
x.atleast)
else:
print 'No exception was raised.'
64. Programming Python
ASC, National Centre for Physics
Exception Handling
Other work can go as usual here.
except EOFError:
print 'nWhy did you do an EOF on me?‘
except ShortInputException, x:
print ‘ nThe input was of length %d, it
should be at least %d' % (x.length,
x.atleast)
else:
print 'No exception was raised.'
65. Programming Python
ASC, National Centre for Physics
Exception Handling
What if we wanted some statements to
execute after the try block whether or
not an exception was raised?
This is done using the finally block.
Note that if we are using a finally
block, we cannot have any except
clauses for the same try block.
66. Programming Python
ASC, National Centre for Physics
Exception Handling
try:
f = file('poem.txt')
while True: # Our usual file-reading block
l = f.readline()
if len(l) == 0:
break
print l,
finally:
print 'Cleaning up...'
f.close()
67. Programming Python
ASC, National Centre for Physics
GUI – Tkinter Overview
Of various GUI options, Tkinter is the
de facto standard way to implement
portable user interfaces in Python
today.
Tkinter’s availability, accessibility,
documentation and extensions have
made it the most widely used Python
GUI solution for many years running.
68. Programming Python
ASC, National Centre for Physics
Tkinter Structure
Tkinter is the simply the name of Python’s
interface to Tk
-- a GUI library originally written for use with the
Tcl programming language.
Python’s Tkinter module talks to Tk, and the
Tk API in turn interfaces with the underlying
window system:
Microsoft Windows
X Windows on Unix
or Macintosh
69. Programming Python
ASC, National Centre for Physics
Tkinter Structure
Python’s Tkinter adds a software layer on top
of Tk that allows Python scripts to call out to
Tk to build and configure interfaces, and
routes control back to Python scripts that
handle user-generated events (e.g., mouse-
clicks).
i.e., GUI calls are internally routed from
Python script, to Tkinter, to Tk; GUI events
are routed from Tk, to Tkinter, and back to a
Python script.
70. Programming Python
ASC, National Centre for Physics
Tkinter Structure
Luckily, Python programmers don’t
normally need to care about all this call
routing going on internally;
They simply make widgets and register
Python functions to handle widget events.
Because of the overall structure, event
handlers are usually known as callback
handlers as the GUI library “calls back”
to Python code when events occur.
71. Programming Python
ASC, National Centre for Physics
Tkinter Structure
Python/Tkinter programs are entirely event-
driven:
They build displays and register handlers for
events, and then do nothing but wait for events to
occur.
During the wait, the Tk GUI library runs an event
loop that watches for mouseclicks, keyboard
presses, and so on.
All application program processing happens in the
registered callback handlers in response to events.
72. Programming Python
ASC, National Centre for Physics
A Tiny GUI example
# Get a widget object
from Tkinter import Label
# Make one
widget = Label(None, text=‘Hello GUI World!’)
# Arrange it
widget.pack()
# Start event loop
widget.mainloop()
73. Programming Python
ASC, National Centre for Physics
A Tiny GUI Example
The above written code is a complete
Python Tkinter GUI program.
When this script is run, we get a simple
window with a label in the middle.
74. Programming Python
ASC, National Centre for Physics
Tkinter Coding Basics
Although the last example was a trivial one
but it illustrates steps common to most
Tkinter programs:
Loads a widget class from the Tkinter module
Makes an instance of the imported Label class
Packs(arrange) the new Label in its parent widget
Calls mainloop to bring up the window and start
the Tkinter event loop
75. Programming Python
ASC, National Centre for Physics
Tkinter Coding Basics
The mainloop method called last puts the
label on the screen and enters a Tkinter wait
state, which watches for user-generated GUI
events.
Within the mainloop function, Tkinter
internally monitors things like the keyboard
and mouse, to detect user-generated events.
Because of this model, the mainloop call here
never returns to our script while the GUI is
displayed on screen.
76. Programming Python
ASC, National Centre for Physics
Tkinter Coding Basics
To display a GUI’s window, we need to call
mainloop.
To display widgets within the window, they
must be packed so that the Tkinter geometry
manager knows about them.
A mainloop without a pack shows an empty
window.
And a pack without a mainloop in a script
shows nothing since the script never enters
an event wait-state.