[FRPythoneers] Object instantiation (newbie question)

Ken Kinder kkinder at tridog.com
Wed Aug 1 15:52:44 MDT 2001


Let me get this right. You're wondering if it would be better for the
user to enter a name like Jon, and creating an object named Jon, like:

	Jon = Hand()

You can do this, but I don't recomend it. You could do this?

	name = get_name()
	exec("%s = Hand()" % name)

But don't do it. Someone could type arbitrary code in as their name and
get it executed.

I think the way you do it currently is fine. If you want a more hardcore
object oriented way to do it, you could create a class called Game with
people at the game:

class Game:
    def __init__(self):
        self.players = {}

    def add_player(self, name):
        self.players[name] = Hand()

... something like that.

DeVerter at robinsonmechanical.com wrote:
> 
> Hi,
>      I am not sure how to handle the objects I am creating in my first
> 'real' Python script - a little black-jack program.  At this point, I am
> instantiating at least two objects, Hand and Card; a Hand() would contain
> Cards().  As you can see from the script below I do achieve creating the
> Hand() objects but they are being stored in the dictionary, player_dict{}.
> This works because I can refer to them by their key but I wonder if it
> would be 'better' to instantiate these objects outside of the list and the
> object name would be the name from get_name().
> 
> In summary:
> 1)  How do I create the objects away from the dictionary using the name
> entered as the object name?
> 2)  Which is better, leaving the objects in the dictionary or instantiating
> them 'in the open'?
> 
> Thanks for your suggestions,
> Mark d.
> 
> ------------
> class Hand:
>      def __init__(self, name):
>           self.cards=[]
>           self.name=name
> 
> class Card:
>      pass
>      # withheld code since its not necessary here.
> 
> def get_name():
>      name=raw_input("Enter name for player %s: " % (player+1))
>      return name
> 
> num_players=input("How many players? ")
> player_dict={}
> 
> for player in range(num_players):
>      player_dict[player]=get_name()
>      player_dict[player]=Hand(player_dict[player])
> 
> -----------------
> 
> BTW:  Acknowledgements to 'How To Think Like A Computer Scientist, Python
> Edition' for the Deck(), Hand() and Card() classes I am using in my silly
> little program.
> 
> _______________________________________________
> This message sent by the FRPythoneers mailing list.
> Unsubscribe: echo unsubscribe | FRPythoneers-request at lists.community.tummy.com
> URL: http://lists.community.tummy.com/mailman/listinfo/frpythoneers



More information about the FRPythoneers mailing list