0% found this document useful (0 votes)
2 views7 pages

Code Classes Notes

The document discusses object-oriented programming concepts in Python, focusing on classes, methods, and inheritance. It explains the use of instance variables, class variables, and magic methods, including examples of how to create and manipulate classes like Employee and Developer. Additionally, it covers method resolution order and the importance of using decorators for property management.

Uploaded by

antran11vn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

Code Classes Notes

The document discusses object-oriented programming concepts in Python, focusing on classes, methods, and inheritance. It explains the use of instance variables, class variables, and magic methods, including examples of how to create and manipulate classes like Employee and Developer. Additionally, it covers method resolution order and the importance of using decorators for property management.

Uploaded by

antran11vn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

DE-CLASSES

Classes FOR MORE CODE LEXAMPLES OPEN Classpractice IN DROPBOX

-
data functions
logically group data functions class are attributes methods
-

of a +

easy to use a build upon a method is a function associated w/ a class

init method -

using the instance (self) to


assign attributes to
any given instance ,
automatically "self" is passed as the first

instance variables are used when data is unique to each instance


argument ,

EXAMPLE: FROM EMPLOYEE CLASS IN CLASS PRACTICE

class
Employee :

definit - (self ,
first last
, ,
pay) :

. first
self =
first

self last last


, RESULT- An Tran .

&company . com

self
pay pay
=
,

self email
.
=
first +!+ last + company com' .

emp-1 Employee (An 'Tran' 300 , 000)


=
, ,

print (emp-1 .
email)

variables that shared


variables
all instances of class
are
among a
-

FOR Employee class , class variables are raises & # of employees



accessed through RAISES # OF EMPLOYEES
class or an-
the
instance
class
of the -
defined
using
self (in a method) -

defined in init -
func

craise amount
-
-

pre-defined at the top of the


using Employee
accessed via

self. raise -
amount
amount
or

page (raise - amount = 1 .


04) -

pre defined
-
at the top of
raise
0)
-

class
Employee Employee : the
page (num-of-emps
,
=

t raise amount 1 04 definit (self first last


pay)
=
- .
,
:
- , ,

when
using
def
self raise
.

instead of
- amount
apply-raise : . first
self =
first

Employee
it
.

allows you
raise amountself
to change
.
pay
=
int
(self-pay * self raise.

amount) self last last


,

the raise amount for each instance (Employee) self


pay
pay
-
=
,

self email
.
=
first +!+ last + company com' .

Employee num-of-emps +=
.
1
METHODDS -

regular methods class methods


, ,
a static methods METHODS
- regular methods CLASS METHODS
accesible
through both the classo the instance
-

automatically has self as the first


argument
STATIC METHODS
-

can call for it


using both
Employee .
method ) AND emp-1 method) .

-
class methods
used when method about the class itself
a isn't
really an instance of a class but about
-

I set raise amount ,


tremoving
-
from between words)
class method add "classmethod" line before the class method
to create a a
creating
-

-
the class is
automatically set as the first
argument (by convention , class is represented by "cls")

Way #1 (to use the class method) modifying the class variable "raise-amount was modified
using
-

a class method
to access a class variable "cs" before
you have to write specifying the actual name
-

example "Is raise-amount" as shown in the


: .
tutorial rid (by Corey Schafer)

Way #2 (to use the class method) make an alternative constructor


-

example (from vid) first and last names and separated by hyphen (t
: a
pay are
-

a class method can be created to return the class w/ the specific values passed in that are

obtained by using the split() method to the


string passed in

STATIC
METHODS
different from
regular methods+ class something automatically passed
methods in that it doesn't have
-

in as the first
argument (class or instance not
IS
passed in)
-created by "Abstatic method creating the static method
adding the line before
-
have
logical connections to the class but don't need class (cs) or instance (self) as an

argument
-

when
you are sure that you don't make use of the class or instance within the method it's
,

better to use a static method


-
behaves like normal functions

EXAMPLE : a day is entered ,


return whether it's a
weekday or not has a logical connection to the

class but doesn't


depend on
anything in the class or depend
,
the instance)
on
COD SURCLASSES =

For full tutorial and more details visit Python OOD Tutorial " by Corey Shaefer

subclass is class that inherits from its and used for


a a
parent class is
-

specialized parts of a class but still needs the general info of the parent class
-

to create a subclass that inherits from another class


?
class Newname/Parent class) : >
-
class Developer (Employee) :

DEMO : dev-1 =
Developer (An ,
'Trans 500, 000 .
, Python')
print (dev-1 full name () .
*

↑ Developer--init-- func.
takes first
Developer doesn't have the
last
, ,
pay prog-log
,

-
method fullname but this code , still ↑
inherited from
runs
successfully and
prints "An Trans
parent func. programming
because this Developer subclass inherits language
class
from its parent ,
Employee
-
METHOD RESOLUTION ORDER : now python looks for methods when subclasses are used
python "walks up the chain of inheritance" to look for methods that aren't found
in a subclass so it searches the classles) that that subclass inherits
,
from this process ,

repeats to define dev-1 , --init-- method is

EXAMPLE: needed but


Developer is
empty so

-
class Developer (Employee) :
Python uses method resolution order to

pass walk up the chain of inheritance searches ,

der-1
L
eloper (An' , "Tran' , 400000) Developer first (doesn't find anything) ,
then

print(help (Developer)) & searches Employee finds it there butif it


>
- of code to
& ,

VERY USEFUL use this line , see wasn't found there Python would
method resolution order (chain of inheritance S

L
check the built in objects class
-

methods class methods static methods defined in the


(builting. object)
-

, , subclass

objects data attributes defined in the subclass


T
-

, ,

methods class methods static methods


, ,
inhenied every python
class inherits from

inherited there it's the base class


objects data attributes ,
-

, ,

creating Developer's--init-- function instead of having to redefine all of the


when
-

parent (Employee)'s attributes (first last pay) then either ,

GOOD FOR MULTIPLE


,

GENERALLY BETTER BECAUSE IT'S


super 1) --init-last pay) - IWHERITANCE
& func inputs here
,
parent's init go
.

Employee -- init Enthlast


.
pay) o FOCUSES ONLY ON INHERITANCE FROM Employee
- ,

is used to call the parent (Employee)'s --


init
-
function
class Developer (Employee) :
T .

def--init-- (self, first, last , pay , prog-lang) :

a subclass of the parent (Employee) class that takes in an extra


programming
-

language
class Manager (Employee) : -a
list of people supervised by each
manager
(instance)
lef--init--(self, first last , , pay-yees
None) = :

-
a subclass of the parent (Employee) class that has a list of
people managed by each

Manager (instance) which you can add


,
+remove people from using methods Manager you in ,

can also
print the full names of
everyone on the employees list because of inheritance and
a method
-
didn't pass an empty list for employees as the --init-- func. input because
a list is a mutable data type (MDT) mutable data types -
lists +dictionaries + sets

MDTs can't be passed as an


argument/parameter because when
they're passed
-
in

any changes made (things added or removed from the MDT) will change the original copy of
the MDT as Python doesn't make copies of MDTs when they're passed in as arguments ,
the
changes made will affect the MDT outside the method too

built-in functions
instance of class
- (True/false)
isinstance -

checks if an
object is an a both return Boolean

issubclass checks if class subclass of class values


another
-

a is a

syntax :

is instance
(myr-1 Manager)
,
issubclass (Developer Employee)
-
checks of mgr-1 is an -

checks if Developer is a subclass of Employee


instance of
Manager

subclasses retain their


parent classles)'s
info but
you can
build onto them without
writing repeated code (from parent classes
MAGIC/DUNDER METHODS
-

Python OOP Tutorial 5 & Corey Shaefer YouTube


-

special methods are called magic methods


-

they're always surrounded by double underscores (called dunders)


-
init is also a magic/dunder method

2 COMMON MAGIC METHODS


-

repr - def--repr--Iself) :

usually used for a clear representation of an object usually


, made for others looking at
your
code
-returns a printable representation of an object
str- > def--str = -(self) :
-

a readable representation for the actual


person coding the
project
men
both usually return strings to recreate - represent objects

def--repr--(self) :
5)

return "Employee (23 %E3:E3') · format (self first, self last self
.
.
,
,
pay)
- T -
placeholders placeholders of first last , pay
-

returning a printable representation of an


Employee object (or
instance)
will run when
you write print(repriemp-11) or
print(emp-1 --repo--
-
S
.

OUTPUT : Employee (An! Trans , 400000)


def--str--(self) :

return 'E3-531 ·
self-email
format (self-full name() ,

- -
placeholders fullname and email
placeholders of

-
returns a readable string repretation of an Employee object (or instance)
will run when you write print (strlemp-1)) or
print lemp-1 --str--
-
.

OUTPUT :
An Tran-AnTran & company .
com

OTHER MAGIC METHODS

-
-me
add > print (int --add--(1 2) print Istr---add--I'a! 'b') BUILT IN DUNDER METHOD
-
. , ,

&
def--add--self other) ,
:

FOR EXAMPLE NOT THE MOST PRACTICAL A BEST


+ other,
- JUST
return
self-pay pay
WAY TO ADD SALARIES

TO RON :
print (emp-1 .
--add--lemp-2)) OR printladd(emp-1 emp-2)) ,
CONT ,

len - the built in len method is also a magic/dunder method


RUN :
print (len ('test')) RESULTE 4

print (test--len--(1) RESULT-4

G
def--len--(self) the
length of instance's
:
- returns an

return len (self-full name() full name (first last name)

-
will
print 1 more character than there actually are because it counts
spaces
EXAMPLE:
emp-1 full name
.
=
An Tran
print (emp-1 .
--len--(l) RESULT :
G -
1234567

print (len (emp-1) ⑦ characters

-ROPERTY
DECORATORS

-
includes getters , setters , deleters , etc.

PROPERTY DECORATOR EXAMPLE :


last

3
def--init--(self , first,
:

self first = first


,

self last = last


initial code
,

first t + + company
1

selfemail last
: com
but occurs when
problem
.

def fullname (self) :


an instance is redefined
returnE3 53 format (self first . ,
, self last)

I
TO FIX THIS
emp-1-first = 'Bob'

emp-1 first
# Bob
=
.

emp-1 .
full name = Bob Tran
make email method structured like fullname
a
similarly
-

emp-1 email
Autrang company
=
.
-
.
com

def email (se(f) :

return 23 [3@
.
email .
com format (self first self last)
- ·
, ,

-
so now to run
you have to add an extra 1) and now
every email attribute is

a method call
TO FIX THIS ISSUE ,
and continue
accessing "email" as an attribute then ...

add decorator
a
property
-

DEFINED By : @ property
-
add a property the line before the method
SO IT WOULD BE

& property
def email (self) :

SETTER EXAMPLE :
-used when
you are
trying to
get first name , last name , + email from

emp-1 fullname .
= An Tran'

to define it write & & full name Setter


-

in this case ->


propertyname-setter -

fullname needs to have decorator added to it as well , for setter to be used


a
property a
-

On it

@ property - added property decorator


def fullname (self) :

return '53531 format /self , first , self last)

& fullname . setter I


adding a setter

def fullname (self, name) : creating another method w/ the same name as the one wy the setter

based
first, last
split (") splitting spaces
= name. = on

first 3

2
self, first =

first name
self last
.
=
last
]-making sure that anything before a space is the

first
a last are defined anything after a space is the last name

for instance
every

DELETER EXAMPLE :

-defined
by doing: propertyname deleter in this .
case > -
&fullname deleter
.

to delete
something do del emp-1 attribute in : this case > def emp-1 full name
-
-
. ·

D
I
& fullname deleter
def fullname (self) :
making another method / the same name as the one
w/theeleter
the deleter
printing something visually
to show that ran

)- clearing first flast for


every fullname of each instance

deleted
(setting it as
None)

what gets run when an attribute is deleted
del emp-1 fullname delle
.
point(emp-1 .
fullname) -RESULT : - name None None

You might also like