Structure accessible by attribute name or index options

2024/10/10 0:23:49

I am very new to Python, and trying to figure out how to create an object that has values that are accessible either by attribute name, or by index. For example, the way os.stat() returns a stat_result or pwd.getpwnam() returns a struct_passwd.

In trying to figure it out, I've only come across C implementations of the above types. Nothing specifically in Python. What is the Python native way to create this kind of object?

I apologize if this has been widely covered already. In searching for an answer, I must be missing some fundamental concept that is excluding me from finding an answer.

Answer

Python 2.6 introduced collections.namedtuple to make this easy. With older Python versions you can use the named tuple recipe.

Quoting directly from the docs:

>>> Point = namedtuple('Point', 'x y')
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)
https://en.xdnf.cn/q/69956.html

Related Q&A

Loading data from Yahoo! Finance with pandas

I am working my way through Wes McKinneys book Python For Data Analysis and on page 139 under Correlation and Covariance, I am getting an error when I try to run his code to obtain data from Yahoo! Fin…

Run Multiple Instances of ChromeDriver

Using selenium and python I have several tests that need to run in parallel. To avoid using the same browser I added the parameter of using a specific profile directory and user data (see below). The p…

numpy 2d array max/argmax

I have a numpy matrix:>>> A = np.matrix(1 2 3; 5 1 6; 9 4 2) >>> A matrix([[1, 2, 3],[5, 1, 6],[9, 4, 2]])Id like to get the index of the maximum value in each row along with the valu…

How do I add a python script to the startup registry?

Im trying to make my python script run upon startup but I get the error message windowserror access denied, but I should be able to make programs start upon boot because teamviewer ( a third-party prog…

Python: How can I filter a n-nested dict of dicts by leaf value?

Ive got a dict that looks something like this:d = {Food: {Fruit : {Apples : {Golden Del. : [Yellow],Granny Smith : [Green],Fuji : [Red], },Cherries : [Red],Bananas : [Yellow],Grapes …

contour plot - clabel spacing

I have trouble with matplotlib / pyplot / basemap. I plot contour lines (air pressure) on a map. I use clabel to show the value of the contour lines. But the problem is: the padding between the value a…

Class-based view has no attribute .as_view() error

Im following this tutorial, trying to make an API for my Products table.Heres my .views/API/apitest.py view:from my_app.views.API.serializers import ProductSerializer from my_app.models import Product …

Ordering query result by numeric strings in django (postgres backend)

I have a table with a name (varchar) field that only holds numeric string and I want to order my queries by this field. But name fields are being ordered by alphabetically but I want them to be ordered…

Resolve argparse alias back to the original command

Im using a subparser/subcommand that has an alias. Im using the dest option for the subparser to store the name of the subcommand so I can get it later.Currently if the subcommands name is reallyLongN…

Django: How do I make fields non-editable by default in an inline model formset?

I have an inline model formset, and Id like to make fields non-editable if those fields already have values when the page is loaded. If the user clicks an "Edit" button on that row, it would…