oop - Initializing Python class with array data -


suppose have code below:

class person(object): """ capture user demographics data"""  def __init__(self, name, address, phone, gender, name_prefix):     """ initialize object """     self.name = name     self.address = address     self.phone = phone     self.gender = gender     self.prefix = name_prefix   def display_userdata(self):     """ returns user data"""     userdata = {'name':self.name, 'address': self.address,                  'phone': self.phone, 'gender': self.gender, 'prefix': self.prefix                }     return userdata 

i can initialize data:

newperson = person("ben", '9999 gotham city, las vegas', '702-000-0000', 'male', 'waiter') 

but have feeling display_userdata() function redundant if re-write __init store dict.

newperson.display_userdata() 

it returns output:

{'address': '9999 gotham city, las vegas',  'gender': 'male',  'name': 'ben',  'phone': '702-000-0000',  'prefix': 'waiter'} 

my questions are:

is there smarter way write __init__ snippet input stored directly python dictionary? don't want call constructor dict key using setattr.

secondly, suppose user has 3 phones or more (variable), how store in array while calling object constructor. think self.phone = ['702-000-000', '413-222-3333' ]

why not create dict directly in init?

class person(object): """ capture user demographics data"""      def __init__(self, name, address, phone, gender, prefix):         """ initialize object """         self.userdata = {'name': name, 'address': address,                  'phone': phone, 'gender': gender, 'prefix': prefix                } 

then

newperson = person(name="ben", address='9999 gotham city, las vegas', phone='702-000-0000', gender ='male', prefix ='waiter') print newperson.userdata 

returns

{'phone': '702-000-0000', 'gender': 'male', 'prefix': 'waiter', 'name': 'ben', 'address': '9999 gotham city, las vegas'} 

to second question, if pass list instead of string phone parameter show list, work?

newperson = person(name="ben", address='9999 gotham city, las vegas', phone=['702-000-0000', '111-827-3509'], gender ='male', prefix ='waiter') print newperson.userdata 

returns

{'phone': ['702-000-0000', '111-827-3509'], 'gender': 'male', 'prefix': 'waiter', 'name': 'ben', 'address': '9999 gotham city, las vegas'} 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -