Special Functions¶
Python provides several special functions to get the metadata of the programs that are being executed.
__name__
- to get the name of the programAll operators are typically nothing but functions. We have already seen
operator
which contain the functions.All the standard classes have special functions called as
__str__
and__repr__
to provide string representation.As we explore collection is future, we will observe special functions for operators such as
in
,not in
,len
etc.We can also use functions (constructors) such as
int
,float
,str
etc to convert the data types.
print(__name__)
__main__
import operator
operator.add?
Docstring: add(a, b) -- Same as a + b.
Type: builtin_function_or_method
int.__str__?
Signature: int.__str__(self, /)
Call signature: int.__str__(*args, **kwargs)
Type: wrapper_descriptor
String form: <slot wrapper '__str__' of 'int' objects>
Namespace: Python builtin
Docstring: Return str(self).
int.__repr__?
Signature: int.__repr__(self, /)
Call signature: int.__repr__(*args, **kwargs)
Type: wrapper_descriptor
String form: <slot wrapper '__repr__' of 'int' objects>
Namespace: Python builtin
Docstring: Return repr(self).
user = '1,123 456 789,Scott,Tiger,1989-08-15,+1 415 891 9002,Forrest City,Texas,75063'
user.split(',')[0]
# Even though user_id is integer, it will be treated as string
# split converts a string to list of strings
'1'
type(user.split(',')[0])
str
# We can use int to convert the data type of user_id
user_id = int(user.split(',')[0])
user_id
1
type(user_id)
int
int.__repr__?
Signature: int.__repr__(self, /)
Call signature: int.__repr__(*args, **kwargs)
Type: wrapper_descriptor
String form: <slot wrapper '__repr__' of 'int' objects>
Namespace: Python builtin
Docstring: Return repr(self).
user = '1,123 456 789,Scott,Tiger,1989-08-15,+1 415 891 9002,Forrest City,Texas,75063'
user.split(',')[0]
# Even though user_id is integer, it will be treated as string
# split converts a string to list of strings
'1'
type(user.split(',')[0])
str
# We can use int to convert the data type of user_id
user_id = int(user.split(',')[0])
user_id
1
type(user_id)
int