Skip to content

Commit fcb4cd2

Browse files
authored
Merge pull request #2 from LearnPythonDiscord/2020-07-21
2020 07 21
2 parents 7698b39 + 507cce9 commit fcb4cd2

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

2020_07_21_course/README.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# 2020-21-2020 Class
2+
3+
## Classes
4+
5+
### What is a class
6+
7+
A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class . An object is created using the constructor of the class (__init__ method). A class is pointless without things called methods and attributes which will be further discussed below.
8+
9+
### Attributes
10+
11+
The simplest way to say what an attribute is would be to show you it, so here it is:
12+
13+
```py
14+
class Car:
15+
def __init__(self, wheels:int) -> None:
16+
self.wheels = wheels
17+
18+
mycar = Car(wheels=4)
19+
print(mycar.wheels)
20+
>>> 4
21+
```
22+
23+
"Wheels" is now an attribute of the class "Car", an attribute is something you can reference throughout your code via your "self" usually defined on the __init__ (method called on object initialisation). There is a difference between instance attributes and class attributes. The simplest way to say this is that instance attributes are attributes assigned in the __init__ method whereas class attributes are defined outside of the constructor, it does get a bit more complex than this but for now that doesnt change anything for this.
24+
25+
### Methods
26+
27+
Methods are simply functions that belong to the class, so if you want to do something with the attributes of the class then you simply make a method so you can interact with the data, i will show an example of updating the amount of wheels a car has (a weird example im aware);
28+
29+
```py
30+
class Car:
31+
def __init__(self, wheels:int) -> None:
32+
self.wheels = wheels # wheels is now an attribute of car
33+
def update_wheels(self, wheels) -> None:
34+
self.wheels = wheels # wheels is now updated with the new value
35+
36+
mycar = Car(wheels=4)
37+
print(mycar.wheels)
38+
>>> 4
39+
mycar.update_wheels(5)
40+
print(mycar.wheels)
41+
>>> 5
42+
```
43+
44+
tldr; a method allows you interact with attributes of a class
45+
46+
### Important notes
47+
48+
#### __init__
49+
50+
This is the feature you will see on pretty much every class in python, this is called the constructor. This is the first method called on the initialisation of the class, as the name suggests, it constructs the object.
51+
52+
### __repr__ and __str__
53+
54+
These methods are both called on the print() function, with __str__ being called first, __str__ is the informal representation of the object in string represenation and then __repr__ is the formal version
55+

0 commit comments

Comments
 (0)