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

Len (x) beats x.len (). Pythons design idea from built-in functions

編輯:Python

The built-in function is Python A major feature of , Use Minimalist Syntax to implement many common operations .

They are predefined in the built-in namespace , Open the box , What you see is what you get .Python It is recognized as a new friendly language , This statement can hold , Built in functions play a key role in this .

for instance , Find string x The length of ,Python The way to write is len(x) , And it's written for lists 、 Objects such as tuples and dictionaries also apply , Just pass in the corresponding parameters .len() Functions are shared .

This is the embodiment of a minimalist philosophy :Simple is better than complex.

however , Some languages don't , For example, in Java in , The string class has a way to find the length , Other classes also have their own methods for finding length , They can't share . Every time I use it , Call... By class or instance .

The same is for string length ,Python Writing :

saying = "Hello world!"
print(len(saying))
# result :12

And in the Java in , It may be written as follows ( simplicity ):

String saying = "Hello world!";
System.out.println(saying.length());
// result :12

Python A prefix expression is used , and Java The suffix expression is used .

Except for length ,Python Some of the built-in functions of can also be found in Java Find the corresponding expression in . for example , Numeric string s Convert to integer number ,Python It can be used int(s) function , and Java It can be used Integer.parseInt(s); Integer numbers are converted to strings ,Python It can be used str(i), and Java Also have String.valueOf(i).

Python Is not bound to a specific class , They are primary objects . and Java Of “ function ” Can't exist without a class , They are just accessories .

From an intuitive point of view ,Python The expression seems to be better . however , They are not comparable , Because these are two language systems , Each has its own category background , It's not easy to make an appointment .

It's just like , It's not because the Latin alphabet is simple , It's better than Chinese characters , Because in expressing meaning , Letter ( Phonetic characters ) It is far inferior to Chinese characters ( Ideograph ) Of . alike , Japan borrowed the radical of Chinese characters to create characters , Although it saves more ink , But also completely lost the meaning .

By analogy ,Python The built-in function of is simple and convenient , But it lost some ideographic functions . Some people are questioning / attack Python When , I also like to talk about it , Think it's Python Design defects of .

This leads to one of the most wanted issues in this paper : Why? Python To be designed as len(x) This prefix expresses , instead of x.len() Such suffix expression ?

in fact , Suffix design is also possible , With Python For example, the two methods in the list :

mylist = [2, 1, 3, 5, 4]
mylist.sort()
print(mylist) # [1, 2, 3, 4, 5]
mylist.reverse()
print(mylist) # [5, 4, 3, 2, 1]

They are all called through list objects , It's not taken out of the built-in namespace . Semantic expression is also very clear , That's right mylist Sort and reverse .

That's exactly how it happens , They also have two half brothers sorted() And reversed(), These two are prefixes .

mylist = [2, 1, 3, 5, 4]
sort_list = sorted(mylist)
print(sort_list) # [1, 2, 3, 4, 5]
reverse_list = reversed(mylist)
print(list(reverse_list)) # [4, 5, 3, 1, 2]

Different writing methods , All doing the same thing ( Regardless of their side effects ). therefore , Suffix syntax is not infeasible , Why not , It must have been a deliberate design .

Back to the previous question : Why len(x) , Instead of x.len(x), It comes from Python What is the design idea of ?

Python The father of Guido van Rossum It's been explained ( See the end of the article for links ), There are two reasons :

  • For some operations , Prefixes are better read than suffixes —— Prefix ( And infix ) Representation has a long history in mathematics , Its visual effect helps mathematicians to think about problems . We can simply put the formula x

    (a + b) Rewrite as x

    a + x*b , But the same thing , Implemented in a native object-oriented way , It's clumsy .

  • When read len(x) when , I just know This is to find the length of an object . It told me two things : The return value is an integer , Parameters are some kind of container . But when it comes to x.len() when , I have to know some kind of container in advance x, It implements an interface , Or inherit an ownership standard len() Class of method . We often see this kind of chaos : A class does not implement a mapping (mapping) Interface , But have get() or keys() Method , Or some non file objects , But I have one write() Method .

After explaining these two reasons ,Guido And summed up as a saying :“I see 'len' as a built-in operation ”. It's not just about len() It's more readable and understandable , And it's all about pulling up len() The status of .

It's like saying , fraction ½ The horizontal line in is one of the lines in mathematics “ built-in ” expression , There's no need to implement any more interfaces or the like , It has shown itself that “ Divide a number by a number ” It means . Different types of numbers ( Integers 、 Floating point numbers 、 Rational number 、 Irrational number …) Share the same operator , There is no need to implement a fractional operation for each type of data .

Elegance is easy to understand Python The philosophy of design ,len() The prefix expression of function is the best embodiment .

  • Let's take a look at the use of slices . Probably the most common use , Namely “ Take before n Bit elements ” or “ From i A bit of rope causes , After taking n Bit elements ”( The former usage , It's actually i == Special use of the start bit ). If these two usages can be implemented without unsightness in the expression +1 or -1, It will be very elegant .
  • Use 0-based How to index 、 Half open interval slice and default matching interval (Python Finally, this method is adopted ), The slicing syntax in the above two cases becomes very beautiful :a[:n] and a[i:i+n], The former is a[0:n] The abbreviation of .

therefore , We can say len(x) beat x.len() , It is supported by a simplification of complexity 、 Pure but profound design ideas .

Object oriented programming language since its invention , I want to simulate the real world we live in . But what kind 、 Interface 、 The object. 、 And how they do it , The poison of these things , Sometimes it blinds us to see the essence of the world .

Table class has the table class to find the length method , The chair class has the chair class to find the length method , inexhaustible , But the reality is really so ? The method of finding length can't be an independent object ? The reason it exists , Because there is “ object ” There is , Not because there is a class .

therefore , I want to say ,len(x) beat x.len(), It also shows Python Insight into the nature of the world .

Find the length of an object , This operation exists independently of the object , Not all of the properties or functions inside the object . Understand... From this perspective , We can understand , Why? Python To design built-in functions ? The built-in function is actually a kind of capture of the essence of the world .

These insightful discoveries , Enough to make us fall in love with the language . Life is too short , I use Python.

The above is all the content shared this time , Want to know more python Welcome to official account :Python Programming learning circle , send out “J” Free access to , Daily dry goods sharing


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