Aug-17-2020, 06:33 PM
With the help of the many tutorials available I am teaching myself OOP. Or at least in the offset, discovering what OOP is all about and how it can structure coding and organises data. I have in general grasped the idea of instantiating classes and writing methods to manipulate data etc. The tutorials go something like this.
AttributeError: 'str' object has no attribute 'memdetails'
because when Lst[0] was instantiated it was changed from a string variable into an object of the Member class, but Lst[0]= "Smith" changed it back into a mere string variable again.
My question was going to be how to generate an instance name from a string variable, but writing this post has brought me to the conclusion that it is not possible, after all you can't name a List or a Tuple or any other object for that matter using a string. I guess instantiating a class is not designed to be used in that way. To get John Smiths details I'm going to have to loop around all the instance names until lastname = Smith is found. And adding or deleting a member would mean code changes.
That can't be right!!
Am I missing something
.
class Members: def __init__(self,lastname,firstname,age,): self.lastname = lastname self.firstname = firstname self.age = age def memdetails(self): return f"{self.firstname} {self.lastname} is {self.age} years old" Lst = ["Smith","John",40,] Mem1 = Members(Lst[0],Lst[1],Lst[2]) print (Mem1.memdetails())This works fine and prints out "John Smith is 40 years old" as expected. But what occurs to me is that I need to know that John Smith is instantiated as Mem1 to get those details. I could of course change the code to
Smith = Members(Lst[0],Lst[1],Lst[2]) print (Smith.memdetails())but I don't want to re-code every time I have a new member. I could try
Lst = ["Smith","John",40,] Lst[0] = Members(Lst[0],Lst[1],Lst[2]) print (Lst[0].memdetails())This works but if Lst[0] is changed in any way, then that instance of John Smith would be lost. For example
Lst = ["Smith","John",40,] Lst[0] = Members(Lst[0],Lst[1],Lst[2]) print (Lst[0].memdetails()) Lst[0]="Smith" print (Lst[0].memdetails())gives an error on executing the second print (Lst[0].memdetails())statement
AttributeError: 'str' object has no attribute 'memdetails'
because when Lst[0] was instantiated it was changed from a string variable into an object of the Member class, but Lst[0]= "Smith" changed it back into a mere string variable again.
My question was going to be how to generate an instance name from a string variable, but writing this post has brought me to the conclusion that it is not possible, after all you can't name a List or a Tuple or any other object for that matter using a string. I guess instantiating a class is not designed to be used in that way. To get John Smiths details I'm going to have to loop around all the instance names until lastname = Smith is found. And adding or deleting a member would mean code changes.
That can't be right!!
Am I missing something
