0
class Atom:
    def __init__(self,x,y,z,element,charge,notused,fx,fy,fz):
        self.x=float(x)
        self.y=float(y)
        self.z=float(z)
        self.element=str(element)
        self.charge=float(charge)
        self.notused=int(float(notused))
        self.fx=float(fx)
        self.fy=float(fy)
        self.fz=float(fz)

    @classmethod
    def from_lammps(self,element,x,y,z):
        self.x=float(x)
        self.y=float(y)
        self.z=float(z)
        self.element=str(element)

I am trying to implement an alternate constructor for class Atom. However, I am not sure how what to do differently in from_lammps() to get an object with the given arguments only.

7
  • Did you check this: possible answer Commented Jan 20, 2020 at 18:58
  • Why don't you want to use **kwargs instead of list of arguments? Commented Jan 20, 2020 at 19:00
  • @maverick6912 that seems to be calling the init method again. Can't associate None to the omitted arguments with the provided answer Commented Jan 20, 2020 at 19:04
  • @fireball.1 did you read this answer Commented Jan 20, 2020 at 19:12
  • 1
    You want positional only parameters/arguments? With different ordering in the call signature? Commented Jan 20, 2020 at 19:35

1 Answer 1

1

You could implement an alternative constructor with only the given arguments like this. Note that that the first argument that's passed to a classmethod is the class being instantiated.

class Atom:
    def __init__(self, x, y, z, element, charge, notused, fx, fy, fz):
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)
        self.element = str(element)
        self.charge = float(charge)
        self.notused = int(float(notused))
        self.fx = float(fx)
        self.fy = float(fy)
        self.fz = float(fz)

    @classmethod
    def from_lammps(cls, element, x, y, z):
        obj = object.__new__(cls)
        obj.x = float(x)
        obj.y = float(y)
        obj.z = float(z)
        obj.element = str(element)
        return obj


from pprint import pprint, pformat

atom1 = Atom(1, 2, 3, 'zinc', '3.1415', 42, '4', '5', '6')
print(f'vars(atom1) =\n{pformat(vars(atom1))}')
print()
atom2 = Atom.from_lammps('silver', '6', '7', '8')
print(f'vars(atom2) =\n{pformat(vars(atom2))}')

Output:

vars(atom1) =
{'charge': 3.1415,
 'element': 'zinc',
 'fx': 4.0,
 'fy': 5.0,
 'fz': 6.0,
 'notused': 42,
 'x': 1.0,
 'y': 2.0,
 'z': 3.0}

vars(atom2) =
{'element': 'silver', 'x': 6.0, 'y': 7.0, 'z': 8.0}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.