Python Class instances from Dictionary Keys

Veröffentlicht am: 19 Februar 2020
auf dem Kanal: 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


Auf dieser Seite können Sie das Online-Video Python Class instances from Dictionary Keys mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Python 360 19 Februar 2020 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 5,191 Mal angesehen und es wurde von 27 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!