Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Function to create new objects of a class?

$
0
0
Hello everyone, just wondering how to go about writing a function that takes string arguments and returns an object of a class, for example:

class Person(object):
   def __init__(self,firstName,lastName):
      self.firstName = firstName
      self.lastName = lastName

   def show(P):
      print(P.firstName,P.lastName)

def stringToObject(string):
   string = string.split()
   fName = string[0]
   lName = string[1]
   return Person(fName,lName)
   


Also how would I access this object? I know if for example I created an object using: Example = Person("John","Smith"), I could access this using John.show() but I have no idea how to access the objects that the function creates, or if the code is even working, or if its the right way to go about it. Any help much appreciated as always.

Thanks in advance!

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>