Trending December 2023 # Python – Drop Multiple Levels From A Multi # Suggested January 2024 # Top 20 Popular

You are reading the article Python – Drop Multiple Levels From A Multi updated in December 2023 on the website Achiashop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Python – Drop Multiple Levels From A Multi

To drop multiple levels from a multi-level column index, use the columns.droplevel() repeatedly. We have used the Multiindex.from_tuples() is used to create indexes column-wise.

At first, create indexes column-wise −

items = pd.MultiIndex.from_tuples([("Col 1", "Col 1", "Col 1"),("Col 2", "Col 2", "Col 2"),("Col 3", "Col 3", "Col 3")])

Next, create a multiindex array and form a multiindex dataframe −

arr = [np.array(['car', 'car', 'car','bike','bike', 'bike', 'truck', 'truck', 'truck']), np.array(['valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC'])] # forming multiindex dataframe dataFrame = pd.DataFrame(np.random.randn(9, 3), index=arr,columns=items)

Label the index −

dataFrame.index.names = ['level 0', 'level 1']

Drop a level at index 0 −

dataFrame.columns = dataFrame.columns.droplevel(0)

We deleted a level at 0 index. After deleting, the level 1 is now level 0. To delete another level, just use the above again i.e.

dataFrame.columns = dataFrame.columns.droplevel(0)

Following is the code

Example import numpy as np import pandas as pd items = pd.MultiIndex.from_tuples([("Col 1", "Col 1", "Col 1"),("Col 2", "Col 2", "Col 2"),("Col 3", "Col 3", "Col 3")]) # multiindex array arr = [np.array(['car', 'car', 'car','bike','bike', 'bike', 'truck', 'truck', 'truck']), np.array(['valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC','valueA', 'valueB', 'valueC'])] # forming multiindex dataframe dataFrame = pd.DataFrame(np.random.randn(9, 3), index=arr,columns=items) # labelling index dataFrame.index.names = ['one', 'two'] print"DataFrame...n",dataFrame print"nDropping a level...n"; dataFrame.columns = dataFrame.columns.droplevel(0) print"Updated DataFrame..n",dataFrame print"nDropping another level...n"; dataFrame.columns = dataFrame.columns.droplevel(0) print"Updated DataFrame..n",dataFrame Output

This will produce the following output −

DataFrame...                      Col 1      Col 2      Col 3                      Col 1      Col 2      Col 3                      Col 1      Col 2      Col 3 one      two car      valueA   0.425077   0.020606   1.148156          valueB  -1.720355   0.502863   1.184753          valueC   0.373106   1.300935  -0.128404 bike     valueA  -0.648708   0.944725   0.593327          valueB  -0.613921  -0.238730  -0.218448          valueC   0.313042  -0.628065   0.910935 truck    valueA   0.286377   0.478067  -1.000645          valueB   1.151793  -0.171433  -0.612346          valueC  -1.358061   0.735075   0.092700 Dropping a level... Updated DataFrame..                      Col 1      Col 2      Col 3                      Col 1      Col 2      Col 3 one      two car      valueA   0.425077   0.020606   1.148156          valueB  -1.720355   0.502863   1.184753          valueC   0.373106   1.300935  -0.128404 bike     valueA  -0.648708   0.944725   0.593327          valueB  -0.613921  -0.238730  -0.218448          valueC   0.313042  -0.628065   0.910935 truck    valueA   0.286377   0.478067  -1.000645          valueB   1.151793  -0.171433  -0.612346          valueC  -1.358061   0.735075   0.092700 Dropping another level... Updated DataFrame..                      Col 1     Col 2     Col 3 one      two car      valueA   0.425077  0.020606  1.148156          valueB  -1.720355  0.502863  1.184753          valueC   0.373106  1.300935 -0.128404 bike     valueA -0.648708 0.944725 0.593327          valueB -0.613921 -0.238730 -0.218448         valueC 0.313042 -0.628065 0.910935 truck valueA 0.286377 0.478067 -1.000645 valueB 1.151793 -0.171433 -0.612346 valueC -1.358061 0.735075 0.092700

You're reading Python – Drop Multiple Levels From A Multi

Build Resnet From Scratch With Python !

This article was published as a part of the Data Science Blogathon

Introduction

There have been a series of breakthroughs in the field of Deep Learning and Computer Vision. Especially with the introduction of very deep Convolutional neural networks, these models helped achieve state-of-the-art results on problems such as image recognition and image classification.

So, over the years, the deep learning architectures became deeper and deeper (adding more layers) to solve more and more complex tasks which also helped in improving the performance of classification and recognition tasks and also making them robust.

But when we go on adding more layers to the neural network, it becomes very much difficult to train and the accuracy of the model starts saturating and then degrades also. Here comes the ResNet to rescue us from that scenario, and helps to resolve this problem.

What is ResNet?

Residual Network (ResNet) is one of the famous deep learning models that was introduced by Shaoqing Ren, Kaiming He, Jian Sun, and Xiangyu Zhang in their paper. The paper was named “Deep Residual Learning for Image Recognition” [1] in 2023. The ResNet model is one of the popular and most successful deep learning models so far.

Residual Blocks

The problem of training very deep networks has been relieved with the introduction of these Residual blocks and the ResNet model is made up of these blocks.

Source: ‘Deep Residual Learning for Image Recognition‘ paper

The problem of training very deep networks has been relieved with the introduction of these Residual blocks and the ResNet model is made up of these blocks.

In the above figure, the very first thing we can notice is that there is a direct connection that skips some layers of the model. This connection is called ’skip connection’ and is the heart of residual blocks. The output is not the same due to this skip connection. Without the skip connection, input ‘X gets multiplied by the weights of the layer followed by adding a bias term.

Then comes the activation function, f() and we get the output as H(x).

H(x)=f( wx + b ) or H(x)=f(x)

Now with the introduction of a new skip connection technique, the output is H(x) is changed to

H(x)=f(x)+x

But the dimension of the input may be varying from that of the output which might happen with a convolutional layer or pooling layers. Hence, this problem can be handled with these two approaches:

· Zero is padded with the skip connection to increase its dimensions.

· 1×1 convolutional layers are added to the input to match the dimensions. In such a case, the output is:

H(x)=f(x)+w1.x

Here an additional parameter w1 is added whereas no additional parameter is added when using the first approach.

These skip connections technique in ResNet solves the problem of vanishing gradient in deep CNNs by allowing alternate shortcut path for the gradient to flow through. Also, the skip connection helps if any layer hurts the performance of architecture, then it will be skipped by regularization.

Architecture of ResNet

There is a 34-layer plain network in the architecture that is inspired by VGG-19 in which the shortcut connection or the skip connections are added. These skip connections or the residual blocks then convert the architecture into the residual network as shown in the figure below.

Source: ‘Deep Residual Learning for Image Recognition‘ paper

Using ResNet with Keras:

Keras is an open-source deep-learning library capable of running on top of TensorFlow. Keras Applications provides the following ResNet versions.

– ResNet50

– ResNet50V2

– ResNet101

– ResNet101V2

– ResNet152

– ResNet152V2

Let’s Build ResNet from scratch:

  Source: ‘Deep Residual Learning for Image Recognition‘ paper

Let us keep the above image as a reference and start building the network.

ResNet architecture uses the CNN blocks multiple times, so let us create a class for CNN block, which takes input channels and output channels. There is a batchnorm2d after each conv layer.

import torch import chúng tôi as nn class block(nn.Module): def __init__( self, in_channels, intermediate_channels, identity_downsample=None, stride=1 ): super(block, self).__init__() self.expansion = 4 self.conv1 = nn.Conv2d( in_channels, intermediate_channels, kernel_size=1, stride=1, padding=0, bias=False ) chúng tôi = nn.BatchNorm2d(intermediate_channels) self.conv2 = nn.Conv2d( intermediate_channels, intermediate_channels, kernel_size=3, stride=stride, padding=1, bias=False ) chúng tôi = nn.BatchNorm2d(intermediate_channels) self.conv3 = nn.Conv2d( intermediate_channels, intermediate_channels * self.expansion, kernel_size=1, stride=1, padding=0, bias=False ) chúng tôi = nn.BatchNorm2d(intermediate_channels * self.expansion) chúng tôi = nn.ReLU() self.identity_downsample = identity_downsample self.stride = stride def forward(self, x): identity = x.clone() x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.conv2(x) x = self.bn2(x) x = self.relu(x) x = self.conv3(x) x = self.bn3(x) if self.identity_downsample is not None: identity = self.identity_downsample(identity) x += identity x = self.relu(x) return x

Then create a ResNet class that takes the input of a number of blocks, layers, image channels, and the number of classes.

blocks, out channel, and strides.

class ResNet(nn.Module): def __init__(self, block, layers, image_channels, num_classes): super(ResNet, self).__init__() self.in_channels = 64 self.conv1 = nn.Conv2d(image_channels, 64, kernel_size=7, stride=2, padding=3, bias=False) chúng tôi = nn.BatchNorm2d(64) chúng tôi = nn.ReLU() self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) # Essentially the entire ResNet architecture are in these 4 lines below self.layer1 = self._make_layer( block, layers[0], intermediate_channels=64, stride=1 ) self.layer2 = self._make_layer( block, layers[1], intermediate_channels=128, stride=2 ) self.layer3 = self._make_layer( block, layers[2], intermediate_channels=256, stride=2 ) self.layer4 = self._make_layer( block, layers[3], intermediate_channels=512, stride=2 ) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(512 * 4, num_classes) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.reshape(x.shape[0], -1) x = self.fc(x) return x def _make_layer(self, block, num_residual_blocks, intermediate_channels, stride): identity_downsample = None layers = [] # we need to adapt the Identity (skip connection) so it will be able to be added # to the layer that's ahead if stride != 1 or self.in_channels != intermediate_channels * 4: identity_downsample = nn.Sequential( nn.Conv2d( self.in_channels, intermediate_channels * 4, kernel_size=1, stride=stride, bias=False ), nn.BatchNorm2d(intermediate_channels * 4), ) layers.append( block(self.in_channels, intermediate_channels, identity_downsample, stride) ) # The expansion size is always 4 for ResNet 50,101,152 self.in_channels = intermediate_channels * 4 # For example for first resnet layer: 256 will be mapped to 64 as intermediate layer, # then finally back to 256. Hence no identity downsample is needed, since stride = 1, # and also same amount of channels. for i in range(num_residual_blocks - 1): layers.append(block(self.in_channels, intermediate_channels))

return nn.Sequential(*layers)

Then define different versions of ResNet

– For ResNet50 the layer sequence is [3, 4, 6, 3].

– For ResNet101 the layer sequence is [3, 4, 23, 3].

– For ResNet152 the layer sequence is [3, 8, 36, 3]. (refer the ‘Deep Residual Learning for Image Recognition‘ paper)

def ResNet50(img_channel=3, num_classes=1000): return ResNet(block, [3, 4, 6, 3], img_channel, num_classes) def ResNet101(img_channel=3, num_classes=1000): return ResNet(block, [3, 4, 23, 3], img_channel, num_classes) def ResNet152(img_channel=3, num_classes=1000): return ResNet(block, [3, 8, 36, 3], img_channel, num_classes)

Then write a small test code to check whether the model is working fine.

def test(): net = ResNet101(img_channel=3, num_classes=1000) device = "cuda" if torch.cuda.is_available() else "cpu" y = net(torch.randn(4, 3, 224, 224)).to(device) print(y.size()) test()

For the above test case the output should be:

The entire code can be accessed here:

Thank you.

Related

How To Tactfully Drop A Client

The adage “the customer is always right” isn’t always true. Demanding and unreasonable clients can reach a point where they’re not worth your time.

Before letting clients go, try to resolve conflicts diplomatically, using tactful and open communication strategies.

If a client relationship is untenable, be honest, professional, and polite when parting ways.

This article is for service-based business owners grappling with a difficult client and considering severing the relationship.

Most service-based businesses have encountered a nightmare client at some point. This person makes outrageous demands of your team and expects them to be met immediately. They don’t respect the due date on the invoice and refuse to pay you on time. And when it comes to communication, this client either pesters you 24/7 or can’t be reached at all.

The old cliche may say the customer is always right, but some problematic clients may not be worth your time. Although you may be hesitant to drop (or “fire”) a client, the temporary loss of income could be in your business’s best interest in the long run.

Here’s a look at what to do when faced with a challenging client, when to know it’s time to part ways, and how to extricate yourself politely and professionally.

Key Takeaway

If you have a consumer-focused business, some strategies for dealing with difficult customers are simply listening, empathizing, lowering your voice and staying calm.

How to resolve conflicts with clients diplomatically

If you’re fed up with a client, it may be tempting to let them go immediately. However, while some clients may be annoying, you may not want to give up on the relationship so fast. Here are a few tips for working things out with your client.

1. Figure out what the problem is with your nightmare client.

Step back from the situation and figure out what the issue truly is with your problematic client. Are they really unbearable to work with or negatively impacting your company’s bottom line? Or is there just something about their personality that rubs you the wrong way?

If the problem comes down to clashing personalities, there may be other arrangements to make. Perhaps another team member could take over the lead role with that client – or maybe you can resolve to tolerate and deal with the individual until their contract runs out.

2. Set boundaries with your difficult client.

It’s always a good idea to reassess your client boundaries regularly. For instance, if you have a client who calls you at all hours of the day and night, you may need to reiterate when you’re willing to take calls and when you aren’t. As another example, if you have a client who regularly asks for revisions or tasks beyond the scope of your agreement, it may be helpful to review the terms of your initial contract.

Firmly but politely restating your boundaries may be enough to salvage the working relationship. If the client refuses to respect your boundaries, this can be a clear sign that it’s time to end the working relationship.

Tip

If you need help fielding client calls, consider using a call center or answering service. We’ll help you find the right one with our comparison of the best call centers and answering services for businesses.

3. Communicate openly with your client.

Your clients can’t read your mind; they won’t know if something they’re doing is bothering you unless you tell them. You’re not doing yourself or them a favor by pretending that everything is fine when it isn’t.

If something is bothering you about your working relationship, you owe it to your client to be honest about it. This is especially true if it’s a long-term client; in this case, you probably want to do everything you can to repair the relationship.

Tip

To improve communication with clients, respond to complaints immediately, implement a two-way communication channel, and monitor social media platforms to find out what others are saying about your business.

Python: Remove Punctuation From String, 4 Ways

One common task when working with text data in Python is removing punctuation marks from strings. Punctuation marks can be a nuisance when performing text analysis or natural language processing tasks, and removing them lets you clean up your data and focus on more important aspects, such as word frequency and sentiment analysis.

To remove punctuation from a string in Python, you can use the str.translate() method with the .maketrans() method. You can also use a “for” loop to construct a new string excluding punctuation marks.

In this guide, we’ll explore different methods and techniques to remove punctuation marks from strings in Python. This will help you choose the most suitable method for your project.

Let’s get into it!

Before we start writing the code for removing punctuation characters from a string, let’s quickly review some of the basic concepts of removing punctuation from a string in Python.

In Python, strings are sequences of characters enclosed in either single or double quotes. These characters can include letters, digits, special characters, or special symbols, such as punctuation marks.

You can use built-in functions and methods specifically designed for Python string manipulation to manipulate strings and perform substitutions to remove that random errant question mark.

Punctuation marks are symbols used in written language to clarify sentence structure. These marks include commas, periods, exclamation marks, question marks, colons, semicolons, and more.

You may want to eliminate punctuation marks from a string for processing purposes, such as text analysis or natural language processing.

The following code is an example of removing punctuation from a string:

import string def remove_punctuation(input_string): # Make a translation table that maps all punctuation characters to None translator = str.maketrans("", "", string.punctuation) # Apply the translation table to the input string result = input_string.translate(translator) return result # Sample string with punctuation marks and spaces text = "Hello, world! This is a sample string with punctuation. And spaces!" # Remove punctuation from the string output = remove_punctuation(text) # Print the original and modified strings print("Original string:", text) print("String without punctuation:", output)

In the example above, the remove_punctuation() function takes an input string and creates a translation table using str.maketrans() that maps every punctuation character to None.

Then it applies the translation table to the input string using the translate() method. The result is a new string without any punctuation marks.

This method also preserves spaces between words, making it suitable for processing text data in various applications.

The output of the above code is:

Original string: Hello, world! This is a sample string with punctuation. And spaces! String without punctuation: Hello world This is a sample string with punctuation And spaces

We’ll now discuss different ways to remove punctuation from a string in Python.

Specifically, we’ll cover the following methods:

Using replace() method

Using translate() method

Using regular expressions

Using “for” loop

You can use the replace() method in Python to remove punctuation marks from a string. This method takes an initial pattern and a final pattern as parameters.

It returns a resultant string where characters of the initial pattern are replaced by characters in the final pattern.

By replacing each punctuation string with an empty string, we can effectively remove them from original string.

This example demonstrates using replace() method to remove punctuation from string:

s = "Hello, World!" s = s.replace(",", "") s = s.replace("!", "") print(s)

When you run this code, it’ll output:

Hello World

In this example, replace() removes the comma and the exclamation mark from the original string “Hello, World!”.

You can also use the translate() method to remove unwanted characters from a string in Python.

This method requires a translation table, which you can create using the maketrans() method. With the translation table set to strip punctuation marks, you can then use the translate() method to get the desired output.

This example shows you how to use the translate() method:

import string def remove_punctuation(input_string): # Make a translator object to replace punctuation with none translator = str.maketrans('', '', string.punctuation) # Use the translator return input_string.translate(translator) test_string = "Hello, World! It's a beautiful day." print(remove_punctuation(test_string))

In this script, we are using the str.maketrans() function to create a translation table, which maps each punctuation character into None. Then we use str.translate() function to apply this table to our string.

When you run this code, it’ll print:

Hello World Its a beautiful day

A regular expression pattern can be a powerful tool for text processing.

You can use the Python re module to create empty strings with a pattern that matches all punctuation marks. You can then use the sub() method to replace them with an empty string.

The following example demonstrates this method:

import re import string def remove_punctuation(input_string): # Make a regular expression that matches all punctuation # Use the regex return regex.sub('', input_string) test_string = "Hello, World! It's a beautiful day." print(remove_punctuation(test_string))

In this script, we’re compiling a regular expression that matches all punctuation. The re.escape(string.punctuation) part is needed because some punctuation string marks have special meaning in regular expression.

The sub() function then replaces any matched pattern string (in this case, any punctuation) with an empty string.

This will output:

Hello World Its a beautiful day

You can use a simple for loop to remove punctuation marks from a string. By iterating through each character in the input string and checking if it is a punctuation, you can build a new string that excludes all the punctuation marks.

The following example shows you how to use for loop to remove punctuation:

import string def remove_punctuation(input_string): # Make an empty string to hold the new string without punctuation no_punct = "" for char in input_string: # If the character is not punctuation, add it to the new string if char not in string.punctuation: no_punct += char return no_punct test_string = "Hello, World! It's a beautiful day." print(remove_punctuation(test_string))

In this script, we’re creating a new string no_punct and filling it with each character from the original string that’s not a punctuation mark.

When you run this code, it’ll output:

Hello World Its a beautiful day

So, all punctuation in the test_string has been removed.

To learn more about string manipulation in Python, check the following video:

Understanding how to manipulate and clean text data, such as removing punctuation from a string, is an essential skill when programming in Python. This is because text data is everywhere, in web pages, files, databases, and more. Therefore, knowing how to process and transform this data is invaluable.

Consider tasks like data analysis, machine learning, or even web development. Often, you’ll find yourself working with text. Punctuation can cause issues in these scenarios. It might skew your analysis or confuse your machine learning algorithm.

By learning how to remove unnecessary symbols, you’re equipping yourself with a powerful tool to prepare your data better. You make your text data cleaner, more uniform, and ready for further processing!

In this section, you’ll find some frequently asked questions you might have when removing punctuation from a string.

The “best” method depends on your specific situation and needs.

For simple, one-off replacements, str.replace() could be sufficient.

If you need to remove all punctuation, using str.translate() with str.maketrans(), or re.sub() with a regular expression, are more efficient.

A for loop can also be used for more control over the process.

Yes, context is key. In some natural language processing tasks, punctuation can provide valuable information about sentence structure or sentiment (like the difference between a statement and a question).

Yes, you can replace punctuation with any string you want, such as a space, using the techniques discussed in this article.

Yes, the re module works with any Unicode characters, so it can be used with text in any language.

However, the string.punctuation constant only includes punctuation commonly used in the English language.

You can customize all the methods mentioned to only remove specific punctuation marks.

For example, with str.replace(), you can specify the exact punctuation you want to replace. In the case of str.translate(), re.sub(), and the for loop method, you would adjust the punctuation list to include only the marks you want to remove.

A Free Drag And Drop WordPress Framework

Building a WordPress theme from scratch is a lot of work, and unless you are a developer, chances are you are getting a ready-made theme for your site. To make it easier for end users to create their own theme, many developers created theme frameworks which allow users to create nice functional themes with consistency and speed and without messing with the code. Unyson is one such theme framework with a drag and drop feature and some interesting feature sets and extensions.

Page Builder with Drag and Drop Support

Building visually appealing pages in WordPress is never an easy task. With Unyson’s visual drag and drop page builder, you can easily create your own fully customized page within minutes. The page builder itself contains a lot of elements like buttons, icons, tabs, sliders, layout options, media shortcodes, etc.

Customizations

Built-in BackUp and Restore Feature

Miscellaneous Features

Detailed Documentation

It won’t be useful if it doesn’t come with any documentation. The good thing is that Unyson comes with a full online documentation where you can refer to master and customize it.

Conclusion

Unyson is relatively new and for a free WordPress framework, it delivers what it promises. But, I would personally like to see some quick official how-to guides on creating or building sites using Unyson as it is a bit difficult for any beginner to get around. Besides that, Unyson is a perfect choice if you want to create professional grade WordPress themes. So go ahead and give it a try. After all, it is free and open source.

Hopefully that helps, and do share your thoughts on this new free drag and drop WordPress framework.

Vamsi Krishna

Vamsi is a tech and WordPress geek who enjoys writing how-to guides and messing with his computer and software in general. When not writing for MTE, he writes for he shares tips, tricks, and lifehacks on his own blog Stugon.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Sign up for all newsletters.

By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.

Coming From A Programming Background? Here’s Your Quick Fire Python Guide To Basics!

This article was published as a part of the Data Science Blogathon.

Introduction

Every time I started to learn a new programming language, I was stuck with books and courses explaining the very basic concept of variables, loops, and functions over and over again. In this article, I will skip these parts and just show you how these things look like in Python so that you can code right away.

Contents:

The obligatory “hello world” – Example

How to install and use Python on your system (very easy)

Python basics (the core of the article)

Python OOP (you might skip this)

How to continue from here

1. “Hello world”

Well, not exactly hello world. We ask the user for his name and greet him in person.

Python Code:



input() takes an argument to prompt at the screen and returns the key input, while print() prints something on the screen. No need to declare a “main” function or include any libraries. Get used to simple when programming in Python.

2. Setup

Setting up Python is pretty straightforward. If you are using Linux Python should already be included with your system. Just try

python ––version

To run Python scripts simply type

python scriptname.py 3. Python basics

Now we are ready to get our feet wet. I’ll show you a (nonsense) code snippet which shows the very basic elements of Python. You can use it as a reference if you are for instance wondering “How do I define a function again?“. I’ll go into the details of each segment right after the snippet.

If can have an elif (else if) and an else part.

Loops: You may loop over a so-called “iterable”. Don’t bother the technical term, basically, you can execute a statement x times by using

for i in range(x)

What is pretty cool though is that you can also use a list instead. Python makes life really easy here. The snippet shows a loop that prints the items of the list 3 times.

The while loop is pretty self-explaining.

Let’s move on to function declaration:

def root(x, y=2):

defines a function with two arguments x and y (with a default value of 2) and returns the yth root of x. You call the function by simply using root().

And that’s it with fundamental Python basics – you are now ready to write your first scripts and experiment a little bit with Python. Stay tuned for object-oriented programming and some hints on where to learn more.

4. Object-oriented programming

If you are in OOP then yes, Python can do this as well. Here is again some code snippet:

# Class definition class Pet: # Class variable sound = "makes some noise" # class constructor def __init__(self, name, animal): chúng tôi = name + " the " + animal # class method def make_noise(self): return chúng tôi + " " + self.sound # Create an object peter = Pet('Peter', 'turtle') print(peter.name) # prints "Peter the turtle" print(peter.make_noise()) # "Peter the turtle makes some noise" # Child classes class Dog(Pet): sound = "barks" # calling the super class def __init__(self, name): super().__init__(name, "dog") spike = Dog("Spike") print(spike.make_noise()) # Spike the dog barks

Here we defined a class named Pet, created a subclass Dog which inherits from Pet, and showed some class methods and variables.

But let’s start with

class Pet:

This is about the same syntax as we already have seen from function definitions. If you use an argument as in

class Dog(Pet):

this class is defined as a subclass, stating its parent class as an argument.

Any code you use indented is treated as code belonging to the class (remember, the indentation replaces the brackets). So “sound” is a variable available only within the class aka a predicate.

We skip the constructor __init__ for a second and start with the class method make_noise(self). You might wonder what that “self” means. It references the object that called this method. So self.sound and chúng tôi refers to the predicate’s sound and name.

The method __init__ is the constructor method. I assume you are familiar with basic OOP, so I just mention at this point that this method is called upon the creation of an object. The usage of chúng tôi and name might be a little bit confusing, but just remember that chúng tôi refers to the predicate stored with the object and name refers to the argument that was passed when calling the method.

You can create an object by object = class(parameters), in this case

peter = Pet('Peter', 'turtle')

This calls the constructor and returns the new object.

To access the predicates, call object.predicate, like

peter.name

Note that there is no distinction between private and public predicates like e.g. in C++.

Calling a method works similarly to an object.method(parameters), see

peter.make_noise()

Now let’s create a child class:

class Dog(Pet)

inherits the predicates and methods by its parent class. You can overwrite any predicates and methods of course. To call the superclass methods you use a “super()” like:

super().__init__(name, "dog")

That’s a short intro to the OOP features of Python to get you going. Of course, there are some more features like overloading, static methods, multiple inheritances, but that would be at least one article on its own.

5. That’s all, folks!

And most important: Have fun coding!

Photo by Hitesh Choudhary on Unsplash

Update the detailed information about Python – Drop Multiple Levels From A Multi on the Achiashop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!