MAKING SOME POOP==Python classes constructor and instantiating; class variables

https://www.youtube.com/watch?v=ZDa-Z5JzLYM   << intro video on POOP

https://www.youtube.com/watch?v=BJ-VvGyQxho&t=1s << class variables.



SYNTAX IS A BIT FUCKED UP FOR PYTHON POOP.


Easiest way to get going:

class Employee:

    pass


Constructor uses odd syntax "self".

I hear self can be anything you want, not sure why they didn't use something like (UserInstantiated)

Self can be anything but everyone uses self

--we require attributes for firstname, lastname, and pay.

class Employee:

    def __init__(self, firstname, lastname, pay):

        self.first

        self.last 

        self.pay

        self.email = first + '.' + last + '@piscesinc.com'

    

Once constructor is set, you instantiate:

emp1 = Employee("charlie", "lamm",50000)

emp2 = Employee("Bob", "Kaake",70000)


To add a method--creating full name, you use self again to grab existing attributes in constructor.

    def __init__(self, firstname, lastname, pay):

        self.first

        self.last 

        self.pay

        self.email = first + '.' + last + '@piscesinc.com'

    def fullname(self):

        return '{} {}'.format(self.first, self.last)

OK dokey!

print(emp1.fullname())

(or--different syntax to do the same thing)

Employee.fullname(emp1)


To add a class variable, add it to the constructor:

class Employee:

    raise_amount = 1.04  #this can be used for all instantiations

    def __init__(self, firstname, lastname, pay):

        self.first

        self.last 

        self.pay

        self.email = first + '.' + last + '@piscesinc.com'

     

 To use a class variable in a class method it has the same "self" syntax. Note that this allows a programmer to clobber this class variable value after creating a class instance

    def give_raise(self):

         self.pay = int(self.pay * self.raise_amount)

    

To disallow this clobber, use the name of the class and not self.

class Employee:

    raise_amount = 1.04  #this can be used for all instantiations

    num_emps = 0

    def __init__(self, firstname, lastname, pay):

        self.first

        self.last 

        self.pay

        self.email = first + '.' + last + '@piscesinc.com'

        Employee.num_emps += 1  #we don't want inst. to clobber this!

A trick to see your class attributes: 

print(Classname.__dict__)


How to do constructor overloads, see this video (it's a bit weird) 

https://www.youtube.com/watch?v=rq8cL2XMM5M&t=402s



Comments

Popular posts from this blog

Python POOP: "name mangling"--how to make class data private or public (odd in Python!)

Python POOP: static, class methods