473,405 Members | 2,167 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Bring object 'out of' Class?

Hello,

I'm currently on the class section of my self-taught journey and have a
question about classes: is it possible to bring a object created
inside the class definitions outside the class so it can be accessed in
the interpreter?

For example, right now I'm working (within Allen Downey's Python
Programmer book) with creating a 'hand' of cards. I want to be able to
deal to 'x' amount of cards to 'x' amount of hands and then be able to
manipulate those hands afterwards. I'm not sure if even what I'm
asking is possible or if I'm getting ahead of myself.

As always, thanks for all your help. My learning is greatly enhanced
with everyone's input on this board. Please feel free to
comment/critique the code...

Here is the section of code that deals hands (but doesn't do anything
past that):

def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''
for i in range(num_of_hands):
handname = Hand('hand%d' % i)
self.deal(handname, num)
print '::::%s::::' % (handname.label), '\n', handname, '\n'

and here is the all of the code:

#!/usr/bin/env python

import random

class Card:
"""represents a playing card
attributes: rank, suit"""

def __init__(self, suit=0, rank=3):
self.suit = suit
self.rank = rank

suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"]
rank_names = [None, "Ace", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Jack", "Queen", "King"]

def __str__(self):
#prints card in format: Rank 'of' Suit#
return '%s of %s' % (Card.rank_names[self.rank],
Card.suit_names[self.suit])

def __cmp__(self, other):
#evaluates which card is ranked higher by suit/rank
#arbitrary definition. depends on the card game
card1 = self.suit, self.rank
card2 = other.suit, other.rank
return cmp(card1, card2)
class Deck:
"""represents a deck of cards. 52 card, 4 suits, 13 cards/suit"""

def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
self.cards.append(card)

def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
return '\n'.join(res)

def pop_card(self):
'''removes a card and returns it to another object'''
return self.cards.pop()

def add_cards(self, card):
#adds a card to an object
return self.cards.append(card)

def shuffle(self):
'''must import random, shuffles the deck'''
random.shuffle(self.cards)

def sort_deck(self):
self.cards.sort()

def deal(self, hand, num):
'''moves cards from one object to another'''
for i in range(num):
hand.add_cards(self.pop_card())

def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''
for i in range(num_of_hands):
handname = Hand('hand%d' % i)
self.deal(handname, num)
print '::::%s::::' % (handname.label), '\n', handname, '\n'


class Hand(Deck):
"""child class of Deck. Represents a hand of cards"""

def __init__(self, label=" "):
self.cards = []
self.label = label

Jun 1 '08 #1
3 1694
dave <sq*************@1ya2hoo3.netwrites:
Hello,

I'm currently on the class section of my self-taught journey and have
a question about classes: is it possible to bring a object created
inside the class definitions outside the class so it can be accessed
in the interpreter?

For example, right now I'm working (within Allen Downey's Python
Programmer book) with creating a 'hand' of cards. I want to be able
to deal to 'x' amount of cards to 'x' amount of hands and then be able
to manipulate those hands afterwards. I'm not sure if even what I'm
asking is possible or if I'm getting ahead of myself.

As always, thanks for all your help. My learning is greatly enhanced
with everyone's input on this board. Please feel free to
comment/critique the code...

Here is the section of code that deals hands (but doesn't do anything
past that):

def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''
for i in range(num_of_hands):
handname = Hand('hand%d' % i)
self.deal(handname, num)
print '::::%s::::' % (handname.label), '\n', handname, '\n'
You need to use a 'return' statement:

def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''
hands = []
for i in range(num_of_hands):
newhand = Hand('hand%d' % i)
self.deal(newhand, num)
hands.append(newhand)
print '::::%s::::' % (handname.label), '\n', handname, '\n'
return Hand
Then you can write:
>>hands = deck.deal_cards(4, 5) # On fait une belotte?
And I don't see the need of defining 'Hand' inside 'Deck'.

HTH

--
Arnaud
Jun 1 '08 #2
On 6/1/08, Arnaud Delobelle <ar*****@googlemail.comwrote:
dave <sq*************@1ya2hoo3.netwrites:
[..]
>
def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''
for i in range(num_of_hands):
handname = Hand('hand%d' % i)
self.deal(handname, num)
print '::::%s::::' % (handname.label), '\n', handname, '\n'
>


You need to use a 'return' statement:
def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''

hands = []

for i in range(num_of_hands):

newhand = Hand('hand%d' % i)
self.deal(newhand, num)
hands.append(newhand)

print '::::%s::::' % (handname.label), '\n', handname, '\n'

return Hand
Should be: return hands
>

Then you can write:
>>hands = deck.deal_cards(4, 5) # On fait une belotte?
[...]
Jun 1 '08 #3
Then you can write:
>
>>>hands = deck.deal_cards(4, 5) # On fait une belotte?

And I don't see the need of defining 'Hand' inside 'Deck'.

HTH
Thanks for the input.

I believe using 'class Hand(Deck):' is to illustrate (in the book)
inheritance and how it can be used. By using 'Hand(Deck)' I can then
use the methods (pop_card, add_cards, etc..) defined in the 'Deck'
class.
Jun 1 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Programmer | last post by:
Hi All Here is my problem I'm using a SQLDataAdapter and DataSet I use the method FillSchema(myDataset, SchemaType.Source) The problem is that when i Check the default Values of the Dataset...
1
by: Bo Xu | last post by:
Object of Combination By Bo Xu Introduction A combination of n things, taken s at a time, often referred as an s-combination out of n, is a way to select a subset of size s from a given set of...
6
by: Squeamz | last post by:
Hello, Say I create a class ("Child") that inherits from another class ("Parent"). Parent's destructor is not virtual. Is there a way I can prevent Parent's destructor from being called when a...
4
by: Davids | last post by:
in my small hangman web project I have a Hangman class which has some methods and properties (int GuessAttempts, string GuessedLetters etc..) which change as the game goes on... Best of all would...
6
by: Paolo Pignatelli | last post by:
I have an aspx code behind page that goes something like this in the HTML view: <asp:HyperLink id=HyperLink1 runat="server" NavigateUrl='<%#"mailto:" &amp;...
9
by: DraguVaso | last post by:
Hi, I want my application to bring another application to the Front. I thought best way to do this was by the Process-model: Dim c As Process = Process.GetCurrentProcess() Dim p As Process...
12
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. ...
8
by: Radx | last post by:
Here in my web application, I have a data entry page with serval controls. Some of the controls have autopostback is set true. But the problem is when two or more people are entering data at the...
3
by: dave | last post by:
Hello, I'm currently on the class section of my self-taught journey and have a question about classes: is it possible to bring a object created inside the class definitions outside the class so...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.