21. A. Classes & Instances Flashcards
What are classes useful for?
Logically group data and functions!
Basic Vocabulary
Data & Functions in relation to classes are called:
…in relation to classes:
Data = Attributes Functions = Method
Looking at this code, what is the class, what is the instance? What is the difference between these terms?
class Employee: pass
emp_1 = Employee() emp_2 = Employee()
print(emp_1)
print(emp_2)
emp_1 and _2 are both instances of the same class “Employee”. A class can have an endless number of instances, which are all unique. E.g., if printed out, the result will return two instance objects which differ!
What is the ‘self’ in a class for?
It is like the iterable variable used for the different instances.
E.g., when you want to add a firstname to a variable manually, you code:
emp_1.first = 'Corey' emp_2.first = 'Alan'
If you create a class called Employee, you can pass the __init__ function several argument, of which the first is always ‘self’ (can also have another name, its just the standard word used). After self, you can specify further arguments, e.g. “first”:
class Employee: def \_\_init\_\_(self, first ): self.first = first
emp_1 = Employee('Corey') emp_2 = Employee('Test')
emp_1.first has been swapped for classname(‘argument’)
What are
a. the attributes and
b. the method
in the following class:
class Employee: def \_\_init\_\_(self, firstName, lastName, pay): self.firstName = firstName self.lastName = lastName self.pay = pay self.email = firstName + '.' + lastName + '@company.com'
def fullname(self): return '{} {}'. format(self.first, self.last)
emp_1 = Employee('Corey' , 'Schafer', 50000) emp_2 = Employee('Test', 'User', 60000)
a.
Everything assigned to the emp_1 =… class:
e.g. (‘Corey’ , ‘Schafer’, 50000)
Remember: Attributes = data in relation to a class
b. def fullname()
It is a function defined within a class, thus called a method.
calling it later, e.g.
print(emp_1.fullname()) will return the name of emp_1
You will need the additional ‘()’ at the end of fullname, because you are calling a method and not an attribute!!!
Imagine an ‘Employee’ class, with a ‘fullname’ method.
What is the difference between printing:
a. emp_1.fullname()
b. Employee.fullname(emp_1)
The printing result is the same!
The only difference is, that in b., by calling the class first, we still have to pass the searched-for employee as an argument