Python Classes and ObjectsPython Classes/ObjectsPython is an object oriented programming language. Show
Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. Create a ClassTo create a class, use the keyword ExampleCreate a class named MyClass, with a property named x: class
MyClass: Try it Yourself » Create ObjectNow we can use the class named MyClass to create objects: ExampleCreate an object named p1, and print the value of x: p1 = MyClass() Try it Yourself » The __init__() FunctionThe examples above are classes and objects in their simplest form, and are not really useful in real life applications. To understand the meaning of classes we have to understand the built-in __init__() function. All classes have a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created: ExampleCreate a class named Person, use the __init__() function to assign values for name and age: class Person: p1 = Person("John", 36) print(p1.name) Try it Yourself » Note:
The The __str__() FunctionThe __str__() function controls what should be returned when the class object is represented as a string. If the __str__() function is not set, the string representation of the object is returned: ExampleThe string representation of an object WITHOUT the __str__() function: class Person: p1 = Person("John", 36) print(p1) Try it Yourself » ExampleThe string representation of an object WITH the __str__() function: class Person: def __str__(self): p1 = Person("John", 36) print(p1) Try it Yourself » Object MethodsObjects can also contain methods. Methods in objects are functions that belong to the object. Let us create a method in the Person class: ExampleInsert a function that prints a greeting, and execute it on the p1 object: class Person: def myfunc(self): p1 = Person("John", 36) Try it Yourself » Note:
The The self ParameterThe It does not have to be named ExampleUse the words mysillyobject and abc instead of self: class Person: def myfunc(abc): p1 = Person("John", 36) Try it Yourself » Modify Object PropertiesYou can modify properties on objects like this: Delete Object PropertiesYou can delete properties on objects by using the Delete ObjectsYou can delete objects by using the The pass Statement
Test Yourself With ExercisesLearn about Python’s Class mechanismPhoto by Chris Ried on UnsplashWhen working on data science projects or any Python programming project, you will most likely find yourself utilizing plenty of self-made functions and variables. You may have even create an entire script filled with functions you created in order to streamline the process of your project. The purpose of these functions can be for numerous things within your code. From cleaning your DataFrame to training a machine learning model. It’s useful to create a ton of functions in order to organize your Python code but there is another way to make your code look and act more presentable — By using a Python Class! What is a Python Class?A Python class is like an outline for creating a new object. An object is anything that you wish to manipulate or change while working through the code. Every time a class object is instantiated, which is when we declare a variable, a new object is initiated from scratch. Class objects can be used over and over again whenever needed. Example: Dating ProfilesIn our case, in our previous articles, we have been writing a series about the creation of a dating algorithm that clusters and sorts dating profiles by using machine learning. See here: In the article above, we go through the entire process of data preprocessing in order to have our data become AI friendly, such as transforming the dating profiles into an array of numbers. The objects, in this case, are the dating profiles that need to be manipulated in order for all of this to happen. This data preprocessing step is achieved through the use of numerous functions. It is not organized in the best way but it gets the job done. However, we can improve the process by utilizing a Python Class.
Class for Dating ProfilesIn order to learn more about class objects and utilizing them, we will be implementing a class object for our AI Dating Algorithm. Let’s organize and clean up the code we used into a Class object. Class Object PurposeFirst, we must ask ourselves — What do we want this class object to do? We want it to:
Basically, we will want it to condense the entire data preprocessing step into a Class object which we can then use for every new dating profile we wish to add. We can use this class object whenever we need to create a new dating profile. Constructing a ClassBefore you create the class, we suggest you import the necessary libraries. For our class, we will be using the following libraries in order to format the new dating profile: import pandas as pd To begin, in order to create a class object, all you have to do is type the following: class CreateProfile: The name of the class is subjective but the general rule regarding the format of the name is to follow something called camelCase. This is the start of our class object from which we will begin building off of. Within the class, tab over to start defining our first function. Usually, when creating a class, you will have to define a function called
class CreateProfile: What is an “__init__” function?An CreateProfile()# ORprofile = CreateProfile() Here we are instantiating the class object and by doing so, we are implicitly calling the
What is “self”?The The Using “self”To further understand the usage of class CreateProfile: As you can see here, we are adding some arguments after Class AttributesWhen assigning these DFs in our # Instantiating the class This will return to us whatever dataset we provided when we instantiated the class. In this case, running this code will return
nothing because We can also run In order to progress to the next step, let’s establish all the class attributes to create our final Class Methods (Functions)Functions that we create within a class are called methods. Functions and methods are essentially the same thing but in the context of class objects, functions are referred to as methods. We will need to create some methods for our class in order to manipulate and utilize the data given. In this case, we will be using a synthetic dataset of dating profiles we created earlier before. See the following article to see the creation of this dataset: This dataset will give us the context from which we will create a new dating profile. Creating a New Dating Profile with a Class MethodOne of the first things we want our class to do is to
create a brand new profile if it wasn’t already provided with one. To do this we can create a new method below the class createProfile: As you can see, we are still using the The above method uses We allow the option to either use random information from the larger dataset to fill in the new profile or enter information manually. After having the profile information entered, the method overwrites the If you wanted to enter new information, you’ll have to reinstantiate the class and run it again from the top. Instantiating the class starts the whole process all over again. Running the Class MethodHere is how we run this method starting from the instantiation step: # Instantiating with the data from the DF of synthetic profiles That is really all we need. Just the two lines of code. When we run this it will either enter random information for the profile, which is the function’s default behavior, or it will prompt us to enter information manually like so: This prompt will appear for every feature that needs informationEither way, the class method will have created a brand new profile for us to manipulate in the form of a DataFrame: The New Dating ProfileMore Class MethodsFor us to create a well-rounded class, it must do more than just create a new dating profile. In that case, we will add the methods that were previously stated in the Explaining each MethodEach method in the class performs a specific function. Given the attributes created in the
Running each method is the same as running the # Running each method after having ran enter_info() Viewing Class AttributesNow that we have run all the methods in our class, we can check the results by looking at the new class attributes that each method used. # Running each attribute to check their results If you were to run this code you will be able to see the class attributes that each method dealt with and their final result (in order): Results of each attribute (Top to Bottom): combined_df, vectorized_text, scaled_profile, formatted_profileAs you can see, the new profile has an index value of 6600 and it is shown how each method manipulated it. We can now refer to each attribute in the class whenever we want and it will contain these results. Importing the ClassOne thing that is also really useful when creating a class is that we can import the class we create into other Python files or notebooks. Just save the Python class in a from your_file_name import CreateProfile Now you can use your Python class whenever you want without copy/pasting the code. ClosingUsing class to streamline our data preprocessing step is extremely useful for anyone starting a data science project. In our case, we needed a way to handle the creation of a new profile and format it as well. The great thing about Python’s class is we can reuse it anytime we want. If we wanted to add another dating profile, then all we have to do is instantiate another class object. This can go on and on until we are satisfied with the amount of new profiles created. Overall, class objects can be utilized to organize your code in your coding projects. Here we only covered the basics of Python’s class and there is still some more concepts to learn. If you want to know more about Python’s class, then click here. Check out the Github in the resources below for the full code if you need to. By now you can probably see the value in creating a Python class for your projects. ResourcesWhat is a class in Python example?Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects.
How do you define a class?a class describes the contents of the objects that belong to it: it describes an aggregate of data fields (called instance variables), and defines the operations (called methods). object: an object is an element (or instance) of a class; objects have the behaviors of their class.
What is a class in Python for beginners?In Python, a class is a blueprint for objects. You can initialize objects by implementing the __init__() method in the class. This way you can create objects with unique values, also known as instance variables. Classes can also have other custom methods.
|