0

I have a code that needs to declare several class attributes as shown below. However, what if I have 100 molecules, would I need to copy and paste the code and manually change the numbers accordingly 100 times? Or is there a way to declare variables with different names according to the for loop counter? For example

For i in range(100):
    self.features_str(i+1)x_a= ...

A quick explanation on what each function does. tensorise_smiles returns 3 tensors (in the form of ndarray) features_to_listedtuple takes in the tensor and another ndarray and returns one ndarray.

What I have to do is create an attribute for each molecule 3 times, for the atom, bond, and edge features. However, the problem is if there are many molecules, I have to copy and paste the code many times, changing 1x to 2x, 3x, ..., 100x,... and so on. Is there a better way to do this?

# Setting up features_d. Features containing SMILES for solvent, ligand, RA
    self.features_d_a = features_d
    # 1,2,3 represents the molecule for the solvent, ligand, RA. x,y,z for atom, bond, edge tensor
    self.features_1x_a, self.features_1y_a, self.features_1z_a = tensorise_smiles(features_d[:, 0])
    self.features_2x_a, self.features_2y_a, self.features_2z_a = tensorise_smiles(features_d[:, 1])
    self.features_3x_a, self.features_3y_a, self.features_3z_a = tensorise_smiles(features_d[:, 2])
    self.features_1x_a = features_to_listedtuple(self.features_1x_a, labels)
    self.features_1y_a = features_to_listedtuple(self.features_1y_a, labels)
    self.features_1z_a = features_to_listedtuple(self.features_1z_a, labels)
    self.features_2x_a = features_to_listedtuple(self.features_2x_a, labels)
    self.features_2y_a = features_to_listedtuple(self.features_2y_a, labels)
    self.features_2z_a = features_to_listedtuple(self.features_2z_a, labels)
    self.features_3x_a = features_to_listedtuple(self.features_3x_a, labels)
    self.features_3y_a = features_to_listedtuple(self.features_3y_a, labels)
    self.features_3z_a = features_to_listedtuple(self.features_3z_a, labels)

Thank you!

Lim Kaizhuo
  • 714
  • 3
  • 7
  • 16
  • Are you familiar with dictionaries and collections.namedtuple? The former is an indispensable part of python that you need to learn to succeed. The latter may help you clean up your code a little. – Mad Physicist Jul 31 '18 at 03:00

1 Answers1

2

You can use setattr.

for i in range(100):
    setattr(self, "features_str{}x_a".format(i), value)

However, I would consider using a dictionary to store all of the data. For example:

d = {}
for i in range(100):
    d["{}x_a".format(i)] = value
self.features = d

This permits you to iterate through all of the features, sort them etc.

GWW
  • 43,129
  • 11
  • 115
  • 108
  • Oh I see, thank you for your insights! By the way, if I have to declare variables as variables (and not attributes in a class), is there an analogous method to setattr that I can use)? – Lim Kaizhuo Jul 31 '18 at 02:44