background preloader

Python Object Oriented

Python Object Oriented
Python has been an object-oriented language since it existed. Because of this, creating and using classes and objects are downright easy. This chapter helps you become an expert in using Python's object-oriented programming support. If you do not have any previous experience with object-oriented (OO) programming, you may want to consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts. However, here is small introduction of Object-Oriented Programming (OOP) to bring you at speed − Overview of OOP Terminology Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. Creating Classes The class statement creates a new class definition. class ClassName: 'Optional class documentation string' class_suite The class has a documentation string, which can be accessed via ClassName. Example Following is the example of a simple Python class − Creating Instance Objects #! #! #! Syntax #! Related:  dev pythonPython

python recipe: open a file, read it, print matching lines . palewire There are a couple great books available free online but it's pretty tough to start stringing all the fundamentals into a problem-solving script all on your own. So why not write up some simple recipes that attack problems common to our particular tribe? One of the ways computer programming can be of great use to a reporter is as a text parser. If it's a one-off effort, you can probably get this done quickly using search tools included in common quality text editors (ex. In that spirit, the following instructions are designed to show you how to use Python to search through a text file (The Sonnets of William Shakespeare), find any lines that contain our sample search term ("love"), and then print out the hits into a new file we can keep as a memento. The one prerequsite for the whole endeavor is that you already have a working installation of Python. If you've got it properly installed, it should return something like Alright, with all that out of the way, let's get to the recipe. 1. 2. #!

Python Sending Email using SMTP Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers. Python provides smtplib module, which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. Here is a simple syntax to create one SMTP object, which can later be used to send an e-mail − import smtplib smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] ) Here is the detail of the parameters: host: This is the host running your SMTP server. An SMTP object has an instance method called sendmail, which is typically used to do the work of mailing a message. The sender - A string with the address of the sender.The receivers - A list of strings, one for each recipient.The message - A message as a string formatted as specified in the various RFCs. Example Here is a simple way to send one e-mail using Python script. #! smtplib.SMTP('', 25) Sending an HTML e-mail using Python #! #!

Multiple Function Arguments - Learn Python - Free Interactive Python Tutorial Every function in Python receives a predefined number of arguments, if declared normally, like this: def myfunction(first, second, third): # do something with the 3 variables ... Execute Code It is possible to declare functions which receive a variable number of arguments, using the following syntax: def foo(first, second, third, *therest): print "First: %s" % first print "Second: %s" % second print "Third: %s" % third print "And all the rest... The "therest" variable is a list of variables, which receives all arguments which were given to the "foo" function after the first 3 arguments. First: 1 Second: 2 Third: 3 And all the rest... [4, 5] It is also possible to send functions arguments by keyword, so that the order of the argument does not matter, using the following syntax: The following code yields the following output: The sum is: 6 Result: 1 The "bar" function receives 3 arguments.

Why are Python's 'private' methods not actually private Python Networking Programming Python provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols. Python also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on. This chapter gives you understanding on most famous concept in Networking - Socket Programming. What is Sockets? Sockets are the endpoints of a bidirectional communications channel. Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on. Sockets have their own vocabulary: The socket Module To create a socket, you must use the socket.socket() function available in socket module, which has the general syntax − s = socket.socket (socket_family, socket_type, protocol=0) Here is the description of the parameters − Server Socket Methods Client Socket Methods

Classes and Objects - Learn Python - Free Interactive Python Tutorial Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes. Classes are essentially a template to create your objects. A very basic class would look something like this: class MyClass: variable = "blah" def function(self): print "This is a message inside the class." Execute Code We'll explain why you have to include that "self" as a parameter a little bit later. myobjectx = MyClass() Now the variable "myobjectx" holds an object of the class "MyClass" that contains the variable and the function defined within the class called "MyClass". Accessing Object Variables To access the variable inside of the newly created object "MyObject" you would do the following: myobjectx.variable So for instance the below would output the string "blah": print myobjectx.variable You can create multiple different objects that are of the same class(have the same variables and functions defined). myobjecty = MyClass() myobjecty.variable = "yackity"

Learn Python The Hard Way, 3rd Edition Python is called an "object-oriented programming language." This means there is a construct in Python called a class that lets you structure your software in a particular way. Using classes, you can add consistency to your programs so that they can be used in a cleaner way. I am now going to teach you the beginnings of object-oriented programming, classes, and objects using what you already know about dictionaries and modules. Here we go. You know how a dictionary is created and used and that it is a way to map one thing to another. Keep this idea of "get X from Y" in your head, and now think about modules. A Python file with some functions or variables in it ..You import that file.And you can access the functions or variables in that module with the . Imagine I have a module that I decide to name and I put a function in it called apple. Once I have this code, I can use the module MyStuff with import and then access the apple function: I can access that the same way:

Python Regular Expressions A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. The module re provides full support for Perl-like regular expressions in Python. We would cover two important functions, which would be used to handle regular expressions. The match Function This function attempts to match RE pattern to string with optional flags. Here is the syntax for this function − re.match(pattern, string, flags=0) Here is the description of the parameters: The re.match function returns a match object on success, None on failure. Example #! When the above code is executed, it produces following result − : Cats are smarter than dogs : Cats : smarter The search Function This function searches for first occurrence of RE pattern within string with optional flags. Here is the syntax for this function: #! #! No match!!

An Introduction to Python Lists You can use the list type to implement simple data structures, such as stacks and queues. stack = [] stack.append(object) object = stack.pop() queue = [] queue.append(object) object = queue.pop(0) The list type isn’t optimized for this, so this works best when the structures are small (typically a few hundred items or smaller). For larger structures, you may need a specialized data structure, such as collections.deque. Another data structure for which a list works well in practice, as long as the structure is reasonably small, is an LRU (least-recently-used) container. lru.remove(item) lru.append(item) If you do the above every time you access an item in the LRU list, the least recently used items will move towards the beginning of the list. Searching Lists The in operator can be used to check if an item is present in the list: if value in L: print "list contains", value To get the index of the first matching item, use index: i = L.index(value) try: i = L.index(value) except ValueError: i = -1

2.6. Image manipulation and processing using Numpy and Scipy — Scipy lecture notes This chapter addresses basic image manipulation and processing using the core scientific modules NumPy and SciPy. Some of the operations covered by this tutorial may be useful for other kinds of multidimensional array processing than image processing. In particular, the submodule scipy.ndimage provides functions operating on n-dimensional NumPy arrays. Image = 2-D numerical array (or 3-D: CT, MRI, 2D + time; 4-D, ...) Here, image == Numpy array np.array Tools used in this tutorial: numpy: basic array manipulationscipy: scipy.ndimage submodule dedicated to image processing (n-dimensional images). Common tasks in image processing: Input/Output, displaying imagesBasic manipulations: cropping, flipping, rotating, ...Image filtering: denoising, sharpeningImage segmentation: labeling pixels corresponding to different objectsClassificationFeature extractionRegistration... More powerful and complete modules: OpenCV (Python bindings)CellProfilerITK with Python bindingsmany more... 2.6.1. 2.6.2. 2.6.3.

L’encoding en Python, une bonne fois pour toute J’avais oublié la zik, je rajoute: Vous avez tous un jour eu l’erreur suivante : UnicodeDecodeError: 'machine' codec can't decode character 'trucmuche' in position x: ordinal not in range(z) Et là, pour vous en sortir, vous en avez chié des ronds de pâté. Le problème vient du fait que la plupart du temps, ignorer l’encoding marche : nous travaillons dans des environnements homogènes et toujours avec des données dans le même format, ou un format plus ou moins compatible. Mais le texte, c’est compliqué, terriblement compliqué, et le jour où ça se gâte, si vous ne savez pas ce que vous faites, vous ne vous en sortirez pas. C’est d’autant plus vrai en Python car : Par défaut, Python plante sur les erreurs d’encoding là où d’autres langages (comme le PHP) se débrouillent pour vous sortir un truc (qui ne veut rien dire, qui peut corrompre toute votre base de données, mais qui ne plante pas).Python est utilisé dans des environnements hétérogènes. Règle numéro 1 : Le texte brut n’existe pas.