Dunder Methods verus builtin methods [duplicate] - python

This question already has answers here:
Difference between len() and .__len__()?
(5 answers)
Closed 7 years ago.
I have two examples:
a = [1,2,3]
b = 4
print (a.__len__())
print (len(a))
print(b.__add__(4))
print (b + 4)
I guess my question is, is there a difference when using __len__ magic method versus the built in len() method? The only time I see people use __len__ is when trying to trying to find the length of an object of a user-created class.
Same with other dunder methods, such as __str__, or __add__ I never seem them used outside of a class or OOP in general.

There are only small differencies. Function is just a function, that call len. Something like
def len(x):
return x.__len__()
Of course, you can override builtin len, but that is dump (maybe except debugging). Only different thing is len(x) is easier to read, and x.__len__ allows you create your own implentation of operator. x.__len__ also can be bit faster, but it is a good reason to use it.
When operator have 2 arguments its implementation do more. a+b at first it tries, whether is callable a.__add__ and if it is not, than tries to call b.__radd__.

Related

Functions in Python with or without parentheses? [duplicate]

This question already has answers here:
What does it mean when the parentheses are omitted from a function or method call?
(6 answers)
Closed 2 years ago.
In Python, there are functions that need parentheses and some that don't, e.g. consider the following example:
a = numpy.arange(10)
print(a.size)
print(a.var())
Why does the size function not need to be written with parentheses, as opposed to the variance function? Is there a general scheme behind this or do you just have to memorize it for every function?
Also, there are functions that are written before the argument (as opposed to the examples above), like
a = numpy.arange(10)
print(np.round_(a))
Why not write a.round_ or a.round_()?
It sounds like you're confused with 3 distinct concepts, which are not specific to python, rather to (object oriented) programming.
attributes are values, characteristics of an object. Like array.shape
methods are functions an object can run, actions it can perform. array.mean()
static methods are functions which are inherent to a class of objects, but don't need an object to be executed like np.round_()
It sounds like you should look into OOP: here is a python primer on methods.
Also, a more pythonic and specific kind of attributes are propertys. They are methods (of an object) which are not called with (). Sounds a bit weird but can be useful; look into it.
arrange returns an ndarray. size isn't a function, it's just an attribute of the ndarray class. Since it's just a value, not a callable, it doesn't take parenthesis.

Isn't the keyword "and" an operator in python? Why? [duplicate]

This question already has answers here:
Why is operator module missing `and` and `or`?
(4 answers)
Closed 4 years ago.
I couldn't find the official glossary of python operators but at least it seems that operator library of python doesn't include and or or keyword. They do have operator.and_, but it's for bitwise and operator(&). What makes me more confused is that they do include is or not keywords as operators.
In short, isn't and(and or) an operator? If it isn't, what is the standard of being an operator in Python? I though I'm pretty familiar with python but this problem confuses me a lot at the moment.
Yes, it's an operator. But it's not like the other operators in the operator module.
and short-circuits (i.e., it evaluates its second argument only if necessary). or is similar. Therefore, neither can be written as a function, because arguments to functions are always fully evaluated before the function is called. In some cases this would make no real difference, but when the second argument contains a function call with side effects (such as I/O), or a lengthy calculation, and's behavior is very different from that of a function call.
You could implement it by passing at least the second argument as a function:
def logical_and(a, b):
if not a:
return a
return b()
Then you could call it as follows:
logical_and(x, lambda: y)
But this is a rather unorthodox function call, and doesn't match the way the other operators work, so I'm not surprised the Python developers didn't include it.

Difference between functions that act alone and those with the "dot" operator [duplicate]

This question already has answers here:
What's the difference between a method and a function?
(41 answers)
Closed 7 years ago.
I am a little confused about functions in Python, and how they are classified. For one, we have functions like print(), that simply encode some instructions and act on input. But also, we have functions like 'str'.capitalize(), that can only act when they have an "executor" attached to them. This might not be a well-informed question, but what are the differences between these forms, and how are they classified?
print() is a function in python3 (in python2 it was a statement), and capitalize() is a method.
Please take a look at this answer to clear things up a little bit.
Python is a multi paradigm language that you can write structural and object oriented. Python has built-in functions and built-in classes; for example when you use sequence of characters between two quotation mark (') you instantiate string class.This instance called object. Objects may contain functions or/and other objects. you can access internal functions or object with DOT.
Python is object oriented. This means we have "objects", which basically enclose their own data, and have their own methods. a String is an example of an object. Another example would be if you have a Person object. You can't just do walk(), you have to do Miles.walk(). You could try walk(Miles). But not everything can walk, so we make the function walk() specific to Person objects.
So yes, Python creators could have made capitalize('str') legal, but they decided to make the capitalize function specific to String objects.
print() is a built in function, you can check that like below..
>>> type(print)
<class 'builtin_function_or_method'>
>>> hasattr(print, '__call__')
True
But capitalize() is method of a str class, you can only use this by using string objects.
>>> hasattr('string', 'capitalize')
True

What method do I use to change the interpreter string representation of a class instance [duplicate]

This question already has answers here:
What is the difference between __str__ and __repr__?
(28 answers)
Closed 8 years ago.
I know
__str__
works for most uses of strings.
But what about when I simply write the instance and press enter in the interpreter?
Currently it returns something like <__main__.class at 0xaea0080>, what method do I use to overwrite that?
Use __repr__. Note also that if __str__ is not specified, it defaults to __repr__, but it's rare for this to be useful if you're using them right.
It's a common convention is that __repr__'s result should either look like a constructor call or be surrouned with <>, but it is not intended to be eval'ed in either case.
Lots of better examples here: Difference between __str__ and __repr__ in Python

Is arr.__len__() the preferred way to get the length of an array in Python? [duplicate]

This question already has answers here:
How do I get the number of elements in a list (length of a list) in Python?
(11 answers)
Closed 13 days ago.
The community is reviewing whether to reopen this question as of 8 days ago.
In Python, is the following the only way to get the number of elements?
arr.__len__()
If so, why the strange syntax?
my_list = [1,2,3,4,5]
len(my_list)
# 5
The same works for tuples:
my_tuple = (1,2,3,4,5)
len(my_tuple)
# 5
And strings, which are really just arrays of characters:
my_string = 'hello world'
len(my_string)
# 11
It was intentionally done this way so that lists, tuples and other container types or iterables didn't all need to explicitly implement a public .length() method, instead you can just check the len() of anything that implements the 'magic' __len__() method.
Sure, this may seem redundant, but length checking implementations can vary considerably, even within the same language. It's not uncommon to see one collection type use a .length() method while another type uses a .length property, while yet another uses .count(). Having a language-level keyword unifies the entry point for all these types. So even objects you may not consider to be lists of elements could still be length-checked. This includes strings, queues, trees, etc.
The functional nature of len() also lends itself well to functional styles of programming.
lengths = map(len, list_of_containers)
The way you take a length of anything for which that makes sense (a list, dictionary, tuple, string, ...) is to call len on it.
l = [1,2,3,4]
s = 'abcde'
len(l) #returns 4
len(s) #returns 5
The reason for the "strange" syntax is that internally python translates len(object) into object.__len__(). This applies to any object. So, if you are defining some class and it makes sense for it to have a length, just define a __len__() method on it and then one can call len on those instances.
Just use len(arr):
>>> import array
>>> arr = array.array('i')
>>> arr.append('2')
>>> arr.__len__()
1
>>> len(arr)
1
Python uses duck typing: it doesn't care about what an object is, as long as it has the appropriate interface for the situation at hand. When you call the built-in function len() on an object, you are actually calling its internal __len__ method. A custom object can implement this interface and len() will return the answer, even if the object is not conceptually a sequence.
For a complete list of interfaces, have a look here: http://docs.python.org/reference/datamodel.html#basic-customization
The preferred way to get the length of any python object is to pass it as an argument to the len function. Internally, python will then try to call the special __len__ method of the object that was passed.
you can use len(arr)
as suggested in previous answers to get the length of the array. In case you want the dimensions of a 2D array you could use arr.shape returns height and width
len(list_name) function takes list as a parameter and it calls list's __len__() function.
Python suggests users use len() instead of __len__() for consistency, just like other guys said. However, There're some other benefits:
For some built-in types like list, str, bytearray and so on, the Cython implementation of len() takes a shortcut. It directly returns the ob_size in a C structure, which is faster than calling __len__().
If you are interested in such details, you could read the book called "Fluent Python" by Luciano Ramalho. There're many interesting details in it, and may help you understand Python more deeply.

Categories