[Experimental Building] python11 phase--NO.1 (unfinished)

A tuple is an immutable data type in Python that is 
used in scenarios where the list data will not be modified once it is initialized.
Tuple can only access the elements inside through the position index,
but sometimes we need to give each element an alias in
order to get the corresponding element through the alias. This challenge requires everyone to implement a simple named Tuple by themselves. The saving path of the

function point module file is /home/shiyanlou/namedtuple.py A NamedTuple class is implemented in the module, and its constructor accepts two parameters, iterable and fields, which are respectively used to pass data and its corresponding alias NamedTuple needs to support the location index and Alias ​​attribute two ways to get data NamedTuple repr output format is similar to "NamedTuple(x=1, y=2)", where x, y are aliases, 1, 2 are data. The implementation in the Python standard library cannot be used, and the related words namedtuple cannot appear in the code. The NamedTuple class can inherit from tuple, but it should be noted that tuple is an immutable data type, and its __new__ method needs to be overridden. In order to get the desired repr output, you need to implement _ _repr__ method import unittest from namedtuple import NamedTuple class TestNamedTuple(unittest.TestCase): def test_features(self): fields = ['x', 'y']

















values = [1, 2]
nt = NamedTuple(values, fields)

self.assertEqual(nt[0], 1)
self.assertEqual(nt[1], 2)

self.assertEqual(nt.x, 1)
self.assertEqual(nt.y, 2)

self.assertEqual(repr(nt), 'NamedTuple(x=1, y=2)')
import unittest
class NamedTuple(tuple):
  def __new__(cls, *args, **kwargs):
      return super(NamedTuple, cls).__new__(cls)
  def __repr__(self):
      pass


# class PositiveInteger(int):
#     def __new__(cls, value):
#         return super(PositiveInteger, cls).__new__(cls, abs(value))
# i = PositiveInteger(-3)
# print(i)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324925269&siteId=291194637