Creating a class in Python
Python is a scripting language which means most will take a more functional approach to achieving their main goal. If you are making a large python program, then maybe it's time to consider using classes.
In the code below, we have a class called 'Apple'.
The first line in the code defines the class by stating the keyword class followed by a unique name for that class, which in this case, is Apple.
In the code below, we have a class called 'Apple'.
The first line in the code defines the class by stating the keyword class followed by a unique name for that class, which in this case, is Apple.
Class variables
Underneath the class definition, we have a class variable. The class variable is a variable that is shared by ALL instances of the class. This means that all instances can also change the class variable, so be cautious of how class variables are used!
Instance methods/variables
Then we get to the __init__() function. This is a special function that is automatically invoked when a class instance is created. In the example below, the __init__() function has two attributes; self and name.
The 'self' attribute represents the instance that is calling the function.
Calling s = Apple("smith") inside the if statement passes to the __init__() method s and "smith" to make __init__(s, "smith")
The 'self' attribute represents the instance that is calling the function.
Calling s = Apple("smith") inside the if statement passes to the __init__() method s and "smith" to make __init__(s, "smith")
Once the instances pass data to the __init__() method, you can see that now each instance will have a unique name value passed in from the method.
self.name = name will be replace with s.name = "smith" and g.name = "granny"
That is a basic class in Python! You can have more methods, both class methods and instance methods, to meet the needs of your program.
self.name = name will be replace with s.name = "smith" and g.name = "granny"
That is a basic class in Python! You can have more methods, both class methods and instance methods, to meet the needs of your program.