Python Class instances from Dictionary Keys

Pubblicato il: 19 febbraio 2020
sul canale di: Python 360
5,191
27

Using Linux, Python, and IDLE I show how you can create class instances from Keys in a Python Dictionary "Dict".


I create 3 employees, with salaries, in a dictionary, and then process that using a for loop to create an instance for each one, that can then have it's pay modified. (I also use setter, and getter methods).


At the end I update the dictionary with the new values for the employee/worker salaries.


The code is on git-hub and I hope it's useful for anyone learning classes/OOP or working with for loops and dictionaries.


Tutorial Notes ###


Hello

Today we are going to use Python,

create a class, (Worker)
add a dict, (employee names, and current salaries)

use part of the keys from the dict as the names of the instances.

We also need to use the split function to get the first part of their names....

So there needs to be : self, name, and pay in the def _init_ function at the start.

We will also use "setter" and "getter" functions - these are the recommended way of keeping data secure in a class

"set_pay" uses *= which means the same as self.pay * self.pay * (1 + percent)

I made a function to create the instances of the class, and process it

100000 + 12% = 112000 = correct

33333 + 12% = 37332 = correct

Note: I made "get_pay" return an "int"

As you can see, I have also added this to github.

We have learned how to use a for loop, with keys and values, from a dict,
and how to work with the values, and then add (update) them back to the original dict.

Note the use of the braces {} when using drivers.update

See "update" function for more details when working with dictionaries.


Ps. If you ever need to sort a dictionary, python doesn't allow it, but you can convert to JSON and use "sort_keys = True"


#dict # sort# #python

Check out the Minimalist online python IDE :
https://epyco.herokuapp.com/
https://epico.herokuapp.com/

Buy Dr Pi a Coffee...or Tea! : https://www.buymeacoffee.com/DrPi


In questa pagina del sito puoi guardare il video online Python Class instances from Dictionary Keys della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Python 360 19 febbraio 2020, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 5,191 volte e gli è piaciuto 27 spettatori. Buona visione!