Categories
Python Answers

How to print all instances of a class with Python?

Sometimes, we want to print all instances of a class with Python.

In this article, we’ll look at how to print all instances of a class with Python.

How to print all instances of a class with Python?

To print all instances of a class with Python, we can use the instances property.

For instance, w write

class A:
    instances = []
    def __init__(self):
        self.__class__.instances.append(self)

to create the A class with the instances attribute list.

Then we call self.__class__.instances.append to append self to the instances attribute when we create an A instance.

Then we can get the value of instances with

print('\n'.join(A.instances))

to print all instances of class A created.

Conclusion

To print all instances of a class with Python, we can use the instances property.

Categories
Python Answers

How to convert string to binary with Python?

Sometimes, we want to convert string to binary with Python.

In this article, we’ll look at how to convert string to binary with Python.

How to convert string to binary with Python?

To convert string to binary with Python, we call the encode method.

For instance, we write

b = "hello world".encode('ascii')                           

to call 'hello world'.encode with 'ascii' to get an ASCII binary string with the same content.

Conclusion

To convert string to binary with Python, we call the encode method.

Categories
Python Answers

How to add surface plots in Python matplotlib?

Sometimes, wwe want to add surface plots in Python matplotlib.

In this article, we’ll look at how to add surface plots in Python matplotlib.

How to add surface plots in Python matplotlib?

To add surface plots in Python matplotlib, we can use the plot_surface method.

For instance, we write

import numpy as np
from mpl_toolkits.mplot3d import Axes3D  
import matplotlib.pyplot as plt
import random

def fun(x, y):
    return x**2 + y

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array(fun(np.ravel(X), np.ravel(Y)))
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

to create the fun function that we use to get the z-axis values.

Then we create “xandyarrays withnp.arange(-3.0, 3.0, 0.05)`.

And we call meshgrid with them to create the X and Y values we want to plot for the x and y axes.

Next, we create the zs array with np.array with the fun function called on the x and y axes values that we get with ravel.

And then we call zs.reshape with X.shape to create the Z axis that we can plot.

Then we call plot_surface with X, Y and Z to plot the surface with the points.

And we call set_xlabel, set_ylabel, and set_zlabel to set the axis labels.

Finally, we call show to show the plots.

Conclusion

To add surface plots in Python matplotlib, we can use the plot_surface method.

Categories
Python Answers

How to read a text file into a list or an array with Python?

Sometimes, we want to read a text file into a list or an array with Python.

In this article, we’ll look at how to read a text file into a list or an array with Python.

How to read a text file into a list or an array with Python?

To read a text file into a list or an array with Python, we can use csv.reader.

For instance, we write

import csv

with open('filename.csv', 'r') as fd:
    reader = csv.reader(fd)
    for row in reader:
        # ...

to open filename.csv with open.

Then we call csv.reader with the fd file handle to read the csv file into an iterator.

And then we use the a for loop to loop through the reader iterator and do what we want with the row.

Conclusion

To read a text file into a list or an array with Python, we can use csv.reader.

Categories
Python Answers

How to use Python try…except as in except?

Sometimes, we want to use Python try…except as in except.

In this article, we’ll look at how to use Python try…except as in except.

How to use Python try…except as in except?

To use Python try…except as in except, we use as to assign the exception thrown to a variable.

For instance, we write

try:
    # ...
except (Exception1, Exception2) as e
    print('error')

to catch instances of Exception1 and Exception2 and assign the exception instance to e in the except block.

Conclusion

To use Python try…except as in except, we use as to assign the exception thrown to a variable.