Welcome | Get started | Dive | Contribute | Topics | Reference | Changes | More

Python crash courses

This section is for people who know the basics of Python but who are not yet experienced experts. It quickly explains certain things you need to know because Lino uses them.

What is sys.argv

Download link: https://gitlab.com/lino-framework/book/-/tree/master/docs/dev/newbies/1.py

import sys

print(sys.argv)  # a list

s = ''

for i in sys.argv:
    s += i

print(s)

What is os.environ

Download link: https://gitlab.com/lino-framework/book/-/tree/master/docs/dev/newbies/2.py

mo = {"a": 2, "b": 2, "c": 6}

print(type(mo))

print(mo['a'])

import os

print(type(os.environ))

print(os.environ['PATH'])

About class inheritance

Download link: https://gitlab.com/lino-framework/book/-/tree/master/docs/dev/newbies/3.py

# class inheritance
"""
>>> x = OldBenz()  # we instantiate an OldBenz
>>> print(x.number_of_wheels)
4
>>> print(x.get_speed())
70
>>> print(x.star_logo)
False

>>> y = OldBenz()  # another instance of OldBenz
>>> y.max_speed = 100
>>> print(y.get_speed())
80
>>> print(x.get_speed())
70

I have two instances of OldBenz, one of them is a bit faster. But they are still
OldBenz instances.

>>> my = VW()
>>> print(my.number_of_wheels)
4
>>> print(my.diesel)
False

>>> print(my.star_logo)
Traceback (most recent call last):
...
AttributeError: 'VW' object has no attribute 'star_logo'

"""


class Vehicle:  # class
    number_of_wheels = None   # a class attribute
    max_speed = 20

    def get_speed(self):  # a method
        """Return the maximum speed."""
        return self.max_speed

    def get_foo(self):  # a method
        raise NotImplementedError


class Bike(Vehicle):  # a subclass, inherts from Vehicle, extends Vehicle
    number_of_wheels = 2


class Car(Vehicle):
    brand = None
    number_of_wheels = 4
    max_speed = 90


class Benz(Car):
    star_logo = True
    brand = "Mercedes"


class OldBenz(Benz):
    star_logo = False

    def get_speed(self):
        return super().get_speed() - 20
        # super_object = super(OldBenz, self)
        # print(type(super_object))
        # meth = super_object.get_speed
        # speed = meth()
        # return speed - 20


class VW(Car):
    brand = "Volkswagen"
    diesel = False


if __name__ == '__main__':
    import doctest
    doctest.testmod()

What means “yield”

Download link: https://gitlab.com/lino-framework/book/-/tree/master/docs/dev/newbies/4.py

""" generator functions

>>> print(f1())
[0, 1, ..., 999]

>>> print(f2())
<generator object f2 at ...>

"""


def f1():
    l = []
    for i in range(1000):
        l.append(i)
    return l


def f2():
    for i in range(1000):
        yield i  # yield ulatama


# for i in f1():
#     print i

# # to iterate =
# for i in f2():
#     print i

if __name__ == '__main__':
    import doctest
    doctest.testmod(optionflags=doctest.ELLIPSIS)