程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python implementation derived built-in immutable types

編輯:Python

1、 How to derive built-in immutable types and modify their instantiation behavior ?

         Actual case :

                 We want to customize a new type of tuple , For incoming iteratable objects , Keep only one of them int Type and the value is greater than 0 The elements of , for example :IntTuple([1, -1, 'abc', 6, ['x', 'y'], 3]) => (1, 6, 3).

                 The derived IntTuple The purpose of the new type is to change the instantiation behavior of the built-in tuples , Because the built-in tuple is passed in [1, -1, 'abc', 6, ['x', 'y'], 3] After iteratible object , Every element will go into tuples, which is not what you want at present .

                 requirement IntTuple It's built in tuple Subclasses of , How to achieve ?

         Solution :

                 Defining classes IntTuple Inherit built in tuple, And implement __new__, Modify the instantiation behavior .

2、 Code demonstration

class IntTuple(tuple): # Inherit built in tuple
# Static construction method ,__new__ Will precede __init__ Called
# Realization tuple The filter ,cls For class objects
def __new__(cls, iterable):
# Use the generator to resolve , Filter non int And less than 0 The data of
g = (x for x in iterable if isinstance(x, int) and x > 0)
return super(IntTuple, cls).__new__(cls, g)
t = IntTuple([1, -1, 'abc', 6, ['x', 'y'], 3])
print(t)
# Output results :
(1, 6, 3)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved