Interest and usefulness of python. Part 2
In the previous article we considered several interesting moments of the python language, of course, they do not exhaust one article, so we will continue.
In one of the comments the following code was considered:
SEX = 'Female', 'Male'
sex = SEX[True]# -> Male
sex = SEX[False]# -> Female
at the beginning of there was no special type, and the values 0 and 1 were used. And when they introduced it, they decided to inherit from the whole.
print (int .__ subclasses __ ()) # ->
But let's return to getting the values of the list, suppose we have the following dаta:
books =[["Sherlock Holmes", "Arthur Conan Doyle", 1986, True, 12.51],
["The Lost World", "Arthur Conan Doyle", 2015, False, 5.95],
["The Art of Computer Programming", "Donald E. Knuth ", 2017, True, 190.54]]
Of course, it's not our way to turn to values on indexed indexes. You can create a constant, for example AUTHOR and specify it, but you can go further:
TITLE_AUTHOR = slice (? 2)
PRICE_IN_STOCK = slice (? 5)
print ([book for book in books if book[PRICE_IN_STOCK]>[True, 10.0]])
We can create the object cut and indicate to him, according to which indices are, the fields of interest to us. We can even have enough bravery to write something like the last line in this block, which displays books in stock and more than 10 whatever. This code will work, since the comparison of lists and tuples occurs lexicographically: first the first elements are compared, then the second ones, and so on, that is, any object whose "in_stock" field is false will be less than the list[True, 10.0], since True> False.
Note: Of course, this code should not be used in projects, and it's better to just limit oneself to obtaining some values by the cut, select the best in the database, either in Pandas, or as a method of the Book class. You can use namedtuple and write a small module where to put methods with similar samples.
We have already considered arguments that can be passed to the function only by the key. Recently, studying bool documentation , I found the postscript:
Changed in version 3.7: x is now a positional-only parameter.
Now in development is PEP 570 , which will open the ability to specify such parameters, it can be useful when the parameter name does not matter, like, bool (), pow (), etc.
The syntax draft looks like this:
def name (positional_only_parameters, /, positional_or_keyword_parameters,
Going back to the bool function, which works just like checking in conditions and cycles, when you execute the code
python performs quite Interesting procedure O of the Boolean value:
If the object implements the __bool __ () method, the result of calling this method
Otherwise, it is checked whether the __len __ () method is implemented, if yes, then it is checked that it returns, if 0 - the result will be False.
If neither method is implemented, it returns True.
a = A ()
print (bool (a)) # -> True
Integers implement the __bool__ method, standard collections do not implement it, but implement the __len__:
print (dir (int)) # ->['__abs__', '__add__', '__and__', '__bool__', '__ceil__',
print(dir(list)) # ->['__add__', '__class__', '__contains__',
В другом комментарии было приведено «нестандартное» поведение атрибутов класса:
def __init __ (self):
a = Example ()
b = Example ()
print (a.arr) # ->
print (b.arr) # ->
print (Example.arr) # ->
It is very important to distinguish attributes of class and object , the attributes of the object are created, EXTREMELY, for the object.
It is important to understand that any fields and methods declared in the class body belong to the class. To create an attribute for an object, you need to assign it to the object, in the class method, via self or in the program text, via the object variable.
If they are confused, let's parse the previous code, it creates two instances of the class, then 1 is added to the arr field through one of the objects. But there is no such attribute in the object, the constructor is empty, so python searches for this attribute in the class and finds it, but it is shared by all instances of the class. That this is the attribute of the class can be verified on the last line, because no error has been generated by the name of this attribute to the class.
When learning a new language, it is important to understand that each language has its own philosophy, and not all languages should have the keyword static. Sometimes a similar mechanism is provided by other mechanisms.
Most brightly the idea that python is not java illustrates that the addition of fields in objects and classes is done through the usual assignment:
def make_title (self):
if self.title == 'Mister':
return 'Mr. '+ self.surname
john = Person ()
john.title = 'Mister'
john.name = 'John'
john.surname = 'Peterson'
john.age = 33
Person.make_title = make_title
print (john.make_title ())
The general recommendation: do not store mutable types as instances of a class, this is fraught, however, if you know what you are doing, then use this functionality all the way, the main thing is to think carefully first and document after.
For example, it is very simple to create a class that stores references to all of its instances:
class RememberAll ():
def __init __ (self):
a = RememberAll ()
b = RememberAll ()
print (RememberAll.instances) # ->[<__main__.RememberAll object at 0x7faa4a5ab7b8>, <__main__.RememberAll object at 0x7faa4a523c88>]
You can implement the class of a physical object and, when you change its characteristics, call methods for recalculating the characteristics of other elements of the system. Either memorize all the sliders on the form and with the shift one move the rest automatically. I do not presume to say that such an implementation is always straightforward, but sometimes it can be useful.
Well, once we touched physics, I want to mention the @ operator. Yes, this is there are . It was introduced for matrix multiplication, which is the most amusing, but, it seems, it is not implemented for any of the standard data types, that is, it was originally introduced only for third-party libraries. But nothing prevents you from adding its support for your data types by implementing the __matmul__, __rmatmul__, __imatmul__
def __init __ (self, name):
self.name = name
def __matmul __ (self, msg):
return "@" + self.name + "" + msg
john = Person ("John")
print (john @ "hello") # -> @John hello
It may be interesting
Situs QQ Online
Situs QQ Online