Tutorial A4 – Solutions¶
1 Can you answer these questions?
What is a Python object?
Everything (which is not considered a syntax element) is considered an object in Python: Variables, functions, modules, …
How would you assign a value to a variable?
Use the =
operator to assign from right to left.
How can you know, something is an object in Python?
Objects have a type. Discover the type by using type(object)
.
How can you know a Python object is a function?
Learn details about a Python object by using help(object)
. Functions can be called as function(arguments)
.
How can you get an overview of all the attributes of an object?
dir(object)
How can you discover all objects currently available?
dir()
2 Call help()
on the built-in Python function help
to see what it does.
[1]:
help(help)
Help on _Helper in module _sitebuiltins object:
class _Helper(builtins.object)
| Define the builtin 'help'.
|
| This is a wrapper around pydoc.help that provides a helpful message
| when 'help' is typed at the Python interactive prompt.
|
| Calling help() at the Python prompt starts an interactive help session.
| Calling help(thing) prints help for the python object 'thing'.
|
| Methods defined here:
|
| __call__(self, *args, **kwds)
| Call self as a function.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
3 Which methods (disregarding double underscore methods __method__
) does a str
object have? Try out those of them with an example of your choice that deal with case-formatting (upper/lower case letters) and explain shortly what they do.
[2]:
# Get all callable attributes (no double underscores)
[
a
for a in dir(str)
if (not a.startswith('__')) # no dunder?
& hasattr(getattr(str, a), "__call__") # callable?
]
[2]:
['capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
[3]:
s = "blind Text"
print(s.capitalize()) # Upper case first letters
print(s.swapcase()) # Invert lower to upper case and vice versa
print(s.lower()) # All lower case
print(s.upper()) # All upper case
print(s.casefold()) # Case less comparison
Blind text
BLIND tEXT
blind text
BLIND TEXT
blind text
4 Which methods (disregarding double underscore methods __method__
) does a complex
object have? Try out all of them with an example of your choice and explain shortly what they do.
[4]:
# Get all callable attributes (no double underscores)
[
a
for a in dir(complex)
if (not a.startswith('__')) # no dunder?
& hasattr(getattr(complex, a), "__call__") # callable?
]
[4]:
['conjugate']
[5]:
c = 1 + 1j
print(c.conjugate)
<built-in method conjugate of complex object at 0x7f6e1846b970>
5 When you call print(string)
, the value of string
is printed to the screen. Call help()
on the built-in Python function print
to see what it does. Can you figure out just by reading the help message how to automatically print an exclamation mark (!
) after the print?
[6]:
help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
[7]:
print("string", end="!")
string!