Lecture 7&8: Objects Flashcards
What is an object?
a collection of properties which can be expressed as variables and functions. With these components, an object can represent something.
How do we call functions within an object?
methods
How do we call variables within an object?
attributes
What is a ‘class’?
a blueprint from which you can make objects. It defines what attributes and methods an object has.
What is the ‘class constructor’ and how do you use this?
With the class constructor, the __init__ function is meant. It is used to create a new object of the type of class. The constructor creates a new variable following the blueprint; it is the builder/constructor.
class ClassName: def \_\_init\_\_(self): # Inside the class constructor # Code only runs when the object is first created
What does the ‘self.’ keyword mean? What is it relevance? When must it be used?
self. refers to the object it is used on.
!You need to add this to every method you want to use in a particular class!
e.g.: class Robot: def \_\_init\_\_(self, name, colour, age): self.n = name self.c = colour self.a = age
def introduce_self(self): return("My name is " + self.n)
robot_1 = Robot(“Tom”, “Purple”, 19)
print(robot_1.introduce_self())
> “My name is Tom”
What are the internal variables? What are the external variables? What is the fundamental difference between these two?
Use this example: class Robot: def \_\_init\_\_(self, name, colour, age): self.n = name self.c = colour self.a = age
def introduce_self(self): return("My name is " + self.n)
robot_1 = Robot(“Tom”, “Purple”, 19)
print(robot_1.introduce_self())
> “My name is Tom”
Internal variables can be whatever you want. When using setters, you change the internal variables.
> in the example, the internal variables are ‘n’, ‘c’ and ‘a’.
External variables are fixed; they cannot be changed.
> in the example, the external variables are ‘name’, ‘colour’ and ‘age’.
What are ‘arguments’?
The variables used within the class constructor (__init__).
e.g. class Robot: def \_\_init\_\_(self, name, colour, age): self.n = name self.c = colour self.a = age