What is a Python Class?
- In object-oriented programming, we write classes that represent real-world things and situations, and create objects based on these classes.
Instantiation:
- Making an object from a class is called instantiation, and we work with instances of a class.
The init Method:
-
A function that’s part of a class is a method.
-
The
__init__method is a special method Python runs automatically whenever we create a new instance based on the defined class.- This method has two leading and trailing underscores.
- init is commonly refered to as the constructor method, because it is used to construct or create objects from the class definition.
-
It takes at least one argument, which is usually called self, and represents the object being created. In other words, self argument means “this particular object”. The constructor can also take additional arguments, which are used to set the object’s attributes.
-
Example: Below is a simple class with a constructor
python
1class Person():
2 def __init__(self, name, age):
3 self.name = name
4 self.age = age
5person = Person('Alice', 30)- In this example, we define a
Personclass with a constructor that takes two arguments: name and age. The constructor sets the name and age attributes of the object using the arguments passed to the constructor. - When we create an instance of the
Personclass, the constructor is called automatically.
Instantiate Multiple Users:
python
1class User:
2 def __init__(self, **kwargs):
3 self.details = kwargs
4
5 def get_details(self):
6 return self.details
7
8user1 = User(firstName = "Harpua",
9 age = 30,
10 email = "hbulldog@student.wcu.edu",
11 major = "CIS",
12 minor = "Cybersecurity")
13
14user2 = User(firstName = "Suzy",
15 age = 25,
16 email = "sgreenberg@student.wcu.edu",
17 major = "Biology",
18 minor = "CIS")
19
20def get_username(email):
21 return email.split("@")[0]
22
23print(user1.get_details())
24print(user2.get_details())
25
26print(get_username(user1.details["email"]))
27print(get_username(user2.details["email"]))- The constructor accepts any number of keyword arguments using the kwargs parameter, and stores them in the details attribute. In other words, those attributes about the user are saved on the object itself (
user1oruser2), and other methods and functions can reach it later. - The
get_detailsmethod, defined in line 5 returns the details attribute, which contains the user’s information.
Output (line breaks added for readability; each dictionary actually prints on a single line):
1{'firstName': 'Harpua',
2'age': 30,
3'email': 'hbulldog@student.wcu.edu',
4'major': 'CIS',
5'minor': 'Cybersecurity'}
6
7{'firstName': 'Suzy',
8'age': 25,
9'email': 'hbulldog@student.wcu.edu',
10'major': 'Biology',
11'minor': 'CIS'}
12
13hbulldog
14sgreenberg