Python syntax for namedtuple

I see the Python syntax for the named element:

Point = namedtuple('Point', ['x', 'y'])

Why is it not so simple:

Point = namedtuple(['x','y'])

Its less detailed,

+4
source share
4 answers

namedtuple is a factory that returns a class. Consider only the expression:

namedtuple(['x','y'])

What will be the name of the class returned by this expression?

+2
source

In general, objects do not know which variables are assigned to them:

# Create three variables referring to an OrderedPair class

tmp = namedtuple('OrderedPair', ['x','y'])  # create a new class with metadata
Point = tmp                                 # assign the class to a variable
Coordinate = tmp                            # assign the class to another var

This is a problem for named tuples. We must pass the class name to the namedtuple () factory function so that the class can get the usable name, docstring and __repr__, all of which have the class name inside it.

, -. Python def class, , ( docstring) .

, def:

def square(x):
    'Return a value times itself'
    return x * x

def ( , "" ):

tmp = lambda x: x*x                         # create a function object
tmp.__name__ = 'square'                     # assign its metadata
tmp.__doc__ = 'Return a value times itself'
square = tmp                                # assign the function to a variable

. class , :

class Dog(object):
    def bark(self):
        return 'Woof!'

( , "" ):

Dog = type('Dog', (object,), {'bark': lambda self: 'Woof'})

, def class, . . , Python, def class :

 survey_results = open('survey_results')      # is this really a duplication?
 company_db = sqlite3.connect('company.db')   # is this really a duplication?
 www_python_org = urllib.urlopen('http://www.python.org')
 radius = property(radius)

, . PEP 359, make, def, class import.

make <callable> <name> <tuple>:
    <block>

:

<name> = <callable>("<name>", <tuple>, <namespace>)

, Guido "", , ( , ).

, , . . , . , : -)

+7

. , , . , - :

c = namedtuple('Point', ['x', 'y'])
do_something_with_this(namedtuple('Point', ['x', 'y']))

, :

namedtuple('Point', 'x y')
+2

namedtuple - , . eval. , .

You need to include the appropriate context as arguments for namedtuplefor this to happen. If you do not specify an argument for the class name, it must be guessed. Programming languages ​​do not like to guess.

With the rules of the Python language, the function namedtuplein this expression ..

>>> Point = namedtuple(['x','y'])

.. does not have access to the variable name ( Point), after which the result is saved after the expression is executed. It has access only to the list items presented as an argument (and to the variables that were previously defined).

+1
source

All Articles