Python namedtuple (named tuples) using instances

Source: Internet
Author: User
Tags python namedtuple

Python namedtuple (named tuples) using instances

#!/usr/bin/python3import Collectionsmytupleclass = collections.namedtuple (' mytupleclass ', [' name ', ' age ', ' job ']) obj = Mytupleclass ("tomsom", page, ' cooker ') print (obj.name) print (obj.age) print (obj.job)

Execution Result:

Tomsom12cooker

Namedtuple object as defined by its name, you can give the tuple a name, depending on the following example:

#!/usr/bin/python3import collectionsperson=collections.namedtuple (' person ', ' name Age gender ') print (' Type of the Person: ', type (PERSON)) bob=person (name= ' Bob ', age=30,gender= ' male ') print (' representation: ', Bob) jane=person (name= ' Jane ', age=29,gender= ' female ') print (' Field by Name: ', Jane.name) for people in [bob,jane]:    print ("%s was%d years old%s"% PE Ople)

Execution Result:

Type of person: <class ' type ' >representation:person (name= ' Bob ', age=30, gender= ' male ') Field by Name:janebob is 30 Years old Malejane are years old female

To explain some of the parameters of nametuple, take person=collections.namedtuple (' person ', ' name of age gender ') as an example, where ' person ' is the name of this namedtuple, The following ' name Age gender ' is a string of three characters separated by spaces telling us that our namedtuple has three elements, named Name,age and gender, respectively. We can create it by Bob=person (name= ' Bob ', age=30,gender= ' male ') this way, which is similar to the use of class objects in Python. also, we can access the elements of namedtuple in such a way as to access the properties of the class object, using Jane.name. The output results are as follows:

however, when using namedtyuple, it is important to note that the names cannot use Python keywords, such as class def, and cannot have duplicate element names, such as: there cannot be two ' age '. If these conditions occur, the program will Error. however, It may not be possible to avoid this when actually used, for example: perhaps our element name is a record that is read from the database, which makes it difficult to guarantee that the Python keyword will not appear. The workaround in this case is to open the Namedtuple rename mode so that it is automatically renamed if a python keyword or duplicate element name is Encountered.

Look at the following code:

Import collectionswith_class=collections.namedtuple (' person ', ' name of age class gender ', Rename=true) print With_class._ Fieldstwo_ages=collections.namedtuple (' person ', ' name of age gender age ', Rename=true) print Two_ages._fields

The output is:

(' name ', ' age ', ' _2 ', ' gender ') (' name ', ' age ', ' gender ', ' _3 ')

We use Rename=true to open the rename Option. You can see that the class in the first collection is renamed ' _2 ', and the repeating age in the second collection is renamed ' _3 ' because the Namedtuple is renamed with the underscore _ plus the number of indexes the element is IN.

An example of a Two-paragraph official document code is included:

1) namedtuple Basic Usage

>>> # Basic example>>> point = Namedtuple ("point", [' x ', ' y ']) >>> p = point (one, y=22) # Instant Iate with positional or keyword arguments>>> p[0] + p[1] # indexable like the plain tuple (one, All) 33>>> x, y = p # Unpack like a regular tuple>>> x, y (one, one) >>> p.x + p.y # fields also accessible by NAME33&G T;>> P # readable __repr__ with a name=value stylepoint (x=11, y=22)

2) Namedtuple combined with CSV and SQLite usage

EmployeeRecord = namedtuple (' employeerecord ', ' name, age, title, department, paygrade ') import csvfor emp in map (employeer ecord._make, csv.reader (open ("employees.csv", "rb"))):p rint (emp.name, emp.title) Import sqlite3conn = Sqlite3.connect ('/companydata ') cursor = conn.cursor () cursor.execute (' SELECT name, age, title, department, paygrade from Employees ') for EMP in map (employeerecord._make, cursor.fetchall ()):p rint (emp.name, Emp.title)

Python namedtuple (named tuples) using instances

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.