User Tools

Site Tools


python

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
python [2021/07/28 18:03] – [Signals] utedasspython [2022/12/05 16:26] (current) utedass
Line 4: Line 4:
   * pyserial -- Comport   * pyserial -- Comport
   * matplotlib -- Matlabliknande plotverktyg   * matplotlib -- Matlabliknande plotverktyg
-  * numpy -- Matlabliknande matte+  * [[python:numpy]] -- Matlabliknande matte
   * pandas -- Importera och exportera till olika filformat, ex CSV, tydligen också för att behandla data   * pandas -- Importera och exportera till olika filformat, ex CSV, tydligen också för att behandla data
  
  
 [[https://docs.python.org/3/reference/|Official reference]] [[https://docs.python.org/3/reference/|Official reference]]
 +
 +====== Saker jag vill ha svar på ======
 +
 +  * Grundläggande datastrukturer i Python
 +  * Grundläggande datastrukturer i NumPy
 +  * Grundläggande datastrukturer i Pandas
 +  * Grundläggande datastrukturer i Matplotlib
 +  * Hur man läser syntaxguide i pythons dokumentation
 +  * Hur man använder context managers
 +  * Vad är generators, hur fungerar yield
 +  * Vem fan kom på syntaxen ''mylist = [x*x for x in range(3)]'' och när kan den användas?
 +  * ^ Verkar vara [[https://www.w3schools.com/python/python_lists_comprehension.asp|List comprehensions]]
 ====== Cheat sheet ====== ====== Cheat sheet ======
  
Line 18: Line 30:
 populated_tuple = (1, 2, "Kalle", 4.32) populated_tuple = (1, 2, "Kalle", 4.32)
 singleton_tuple = (3,) singleton_tuple = (3,)
 +print(populated_tuple[2]) # Prints Kalle
  
 # Ranges are also immutable # Ranges are also immutable
Line 45: Line 58:
 all_keys = list(my_dict) all_keys = list(my_dict)
 leet = my_dict['shit'] leet = my_dict['shit']
 +
 +# Dictionaries can be unpacked and used as arguments to a function
 +dude = {a: 4, b: 5}
 +function_that_takes_a_and_b(**dude)
  
 # Set types must contain hashable objects. They are not ordered and cannot be indexed # Set types must contain hashable objects. They are not ordered and cannot be indexed
Line 69: Line 86:
 </code> </code>
  
-====== Parser ======+====== Classes and objects ====== 
 + 
 +<code python> 
 + 
 +# Name mangling for double underscore and less than one trailing underscores 
 +class Foo(object): 
 +    yo = None     # => foo_object.yo 
 +    _yo = None    # => foo_object._yo 
 +    __yo = None   # => foo_object._Foo__yo 
 +    __yo__ = None # => foo_object.__yo__ 
 + 
 + 
 +# To copy an object 
 +import copy 
 +inst2 = copy.copy(inst1) 
 +</code> 
 + 
 + 
 +====== Argument parser ======
  
 <code python> <code python>
Line 114: Line 149:
 ====== Exceptions ====== ====== Exceptions ======
 [[https://docs.python.org/3/tutorial/errors.html]] [[https://docs.python.org/3/tutorial/errors.html]]
 +
 +[[https://docs.python.org/3/library/exceptions.html|Predefined exceptions]]
  
 <code python> <code python>
Line 122: Line 159:
 except IndexError: except IndexError:
   print("Index out of range! :(")   print("Index out of range! :(")
 +
 +
 +a_list = ['yo', 'man']
 +try:
 +  print(a_list[3])
 +except Exception as e:
 +  print("Ett fel har uppstått...")
 +  print(e)
 +  print(type(e))
 </code> </code>
  
Line 128: Line 174:
 raise ValueError("Passed array is not of the right shape") raise ValueError("Passed array is not of the right shape")
 </code> </code>
 +
 +====== Decorators ======
 +Syntactic sugar based on functions that return function objects.
 +
 +[[https://www.programiz.com/python-programming/decorator|Good guide]], much of the info here is stolen from this site.
 +
 +===== Basics =====
 +
 +<code python>
 +# Given this function, which is called a decorator function
 +def my_decorator(func):
 +    def wrapper():
 +        print("I got decorated!")
 +        func()
 +    return wrapper
 +
 +# Then one could write something like this
 +def boring():
 +    print("Normal function")
 +    
 +pimped_boring = my_decorator(boring)
 +pimped_boring()
 +
 +# Or one could overwrite the boring function name
 +def boring():
 +    print("Normal function")
 +boring = my_decorator(boring)
 +
 +# which is equivalent to write this short-cut syntax
 +@my_decorator
 +def boring():
 +    print("Normal function")
 +</code>
 +
 +===== Chaining =====
 +
 +<code python>
 +# Given the two decorators
 +def star(func):
 +    def inner(*args, **kwargs):
 +        print("*" * 30)
 +        func(*args, **kwargs)
 +        print("*" * 30)
 +    return inner
 +
 +
 +def percent(func):
 +    def inner(*args, **kwargs):
 +        print("%" * 30)
 +        func(*args, **kwargs)
 +        print("%" * 30)
 +    return inner
 +    
 +# Then 
 +@star
 +@percent
 +def printer(msg):
 +    print(msg)
 +    
 +# is equivalent to
 +def printer(msg):
 +    print(msg)
 +printer = star(percent(printer))
 +</code>
 +===== Property decorator and setter decorators =====
 +[[https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work-in-python|Explained at stackoverflow]]
 +
 +<code python>
 +class MyClass(object):
 +    def __init__(self):
 +        self._my_property_value = None # Placeholder variable, so getter function works
 +        self.my_property = 123 # Will call the proper setter function
 +        
 +    @property
 +    def my_property(self):
 +        return self._my_property_value
 +        
 +    @my_property.setter
 +    def my_property(self, value):
 +        if value < 0:
 +            self._my_property_value = -value * 10
 +        else:
 +            self._my_property_value = value/10
 +            
 +my_instance = MyClass()
 +my_instance.my_property = -30
 +print(my_instance.my_property) # Prints 300
 +</code>
 +
 +
 +====== tkinter ======
 +[[https://tkdocs.com/tutorial/menus.html|Good site]]
 +
 +[[https://tcl.tk/man/tcl8.6/TkCmd/contents.htm|tk reference]]
 +
 +[[https://web.archive.org/web/20200201190621/http://effbot.org/tkinterbook/text.htm|Archived tutorial from effbot.org]]
 +
python.1627495383.txt.gz · Last modified: 2022/09/12 00:30 (external edit)

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki