21. A. Classes & Instances Flashcards

1
Q

What are classes useful for?

A

Logically group data and functions!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Basic Vocabulary

Data & Functions in relation to classes are called:

A

…in relation to classes:

Data = Attributes
Functions = Method
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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)

A

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!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the ‘self’ in a class for?

A

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’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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

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!!!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Imagine an ‘Employee’ class, with a ‘fullname’ method.

What is the difference between printing:

a. emp_1.fullname()
b. Employee.fullname(emp_1)

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly