Python Basic Grammar Note 2

Source: Internet
Author: User

List operation:

ten_things =  "Apples oranges crows telephone light sugar" print  "Wait  there are not 10 things in that list. let ' S fix that. " Stuff = ten_things.split ('   ') more_stuff = ["Day",  "Night",  "Song",  " Frisbee ", " Corn ", " Banana ", " Girl ", " Boy "]while len (stuff)  != 10:     next_one = more_stuff.pop ()     print  "adding: ",  next_one    stuff.append (Next_one)     print  "There are  %d items now. "  % len (stuff) print  "there we go: ", stuffprint  "let" s do  Some things with stuff. " Print stuff[1]print stuff[-1] # whoa! fancyprint stuff.pop () print  '   '. Join (stuff)  # what? cool!print  ' # '. Join (stuff[3:5])  # super stellar!>>> stuff = {' name ':  ' Zed ',  ' age ':  39,  ' height ':  6 * 12 + 2}>>> print stuff[' name ']zed> >> stuff[1] =  "Wow" >>> stuff[2] =  "Neato" >>> print  stuff[1]wow>>> print stuff[2]neato>>> stuff{' city ':  ' San  Francisco ', 2:  ' Neato ',  ' name ':  ' Zed ', 1:  ' Wow ',  ' age ': 39,  ' Height ':  74}>>> del stuff[' city ']>>> del stuff[1]>>>  DEL STUFF[2]

Use of the class:

#coding =utf-8class Employee: ' base class for all employees ' Empcount = 0 def __init__ (self, Name, salary): Self.name = name sel F.salary = Salary Employee.empcount + 1 def displaycount (self): print "Total Employee%d"% Employee.empcou NT Def displayemployee (self): print "Name:", Self.name, ", Salary:", self.salary "create first object of Employee class" EMP1 = Emp Loyee ("Zara", 2000) "Create a second object of the employee class" EMP2 = Employee ("Manni", 5000)

__DICT__: Properties of the Class (contains a dictionary, consisting of the data properties of the Class)

__DOC__: Document string for Class

__NAME__: Class name

__MODULE__: The module where the class definition resides (the full name of the class is ' __main__.classname ', if the class is in an import module mymod, then classname.__module__ equals Mymod)

__BASES__: All parent classes of a class make up elements (containing a tuple of all the parent classes)

When the object is created, a reference count is created, and when the object is no longer needed, that is, the reference count of the object becomes 0 o'clock, and it is garbage collected. However, recycling is not "immediate", and the interpreter uses the garbage object to reclaim the memory space at the appropriate time.


destructor __del__, __del__ is called when the object dies, and the __del__ method runs when the object is no longer being used:

Class Point:def __init (self, x=0, y=0): self.x = x self.y = y def __del__ (self): class_name = self.__ class__.__name__ print class_name, "destroyed"

Inheritance of the class:

Class Parent: # defines PARENTATTR = def __init__ (self): print "Call parent class constructor" Def Parentmethod (self): print ' Call parent class method ' Def setAttr (self, attr): parent.parentattr = attr def getAttr (self): print "Parent class Property:", PARENT.P Arentattrclass Child (Parent): # define Subclass def __init__ (self): print "Call Subclass construction Method" Def childmethod (self): print ' call subclass Methods Child Method '

Issubclass ()-Boolean function to determine whether a class is a subclass of another class or descendant class, syntax: Issubclass (SUB,SUP)

Isinstance (obj, Class) Boolean function returns True if OBJ is an instance object of class or is an instance object of class subclass.

Operator Overloading:

def __add__ (self,other): Return Vector (SELF.A + other.a, self.b + other.b) class Justcounter:__secretcount = 0 # Private variable pu Bliccount = 0 # public variable

__init__ (self [, args ...])

constructor function

Simple invocation method: obj = ClassName (args)

__del__ (self)

destructor method, deleting an object

Simple method of invocation: Dell obj

__repr__ (self)

Translates into a form for the interpreter to read

Simple method of invocation: Repr (obj)

__str__ (self)

Used to convert a value into a form suitable for human reading

Simple method of invocation: str (obj)

__cmp__ (self, x)

Object comparison

Simple Invocation method: CMP (obj, x)


STR () generally converts a value into a string.

Repr () is to turn an object into a string display, note that only the display is used, and some objects are not directly meant to be converted into strings. such as list,dict using STR () is invalid, but using repr can, this is to see what values they have, for display purposes.


Regular Expressions:

Import reline = "Cats is smarter than dogs" Matchobj = Re.match (R ' (. *) is (. *?). * ', line, re. M|re. I) If Matchobj:print "Matchobj.group ():", Matchobj.group () print "Matchobj.group (1):", Matchobj.group (1) print " Matchobj.group (2): ", Matchobj.group (2) else:print" No match!! "

Output:

Matchobj.group (): Cats is smarter than dogs

Matchobj.group (1): Cats

Matchobj.group (2): Smarter


Re.match matches only the beginning of the string, if the string does not begin to conform to the regular expression, the match fails, the function returns none, and Re.search matches the entire string until a match is found.

Regular expression substitution:

Phone = "2004-959-559 # This is Phone number" # Delete Python-style commentsnum = re.sub (R ' #.*$ ', "", phone) print "Phone Nu M: ", num# Remove anything other than Digitsnum = Re.sub (R ' \d '," ", phone) print" Phone num: ", num

Re. I make the match case insensitive

Re. L do localization identification (locale-aware) matching

Re. M Multiple lines match, affect ^ and $

Re. S make. Match all characters, including line breaks

Re. U resolves characters based on the Unicode character set. This sign affects \w, \w, \b, \b.

Re. X This flag is given by giving you a more flexible format so that you can write regular expressions more easily.


[...] used to represent a set of characters, listed separately: [AMK] matches ' a ', ' m ' or ' K '

[^...] characters not in []: [^ABC] matches characters other than a,b,c.







Python Basic Grammar Note 2

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.