python類與物件練習題撲克牌

2022-03-14 13:56:21 字數 2162 閱讀 6688

#定義乙個撲克類,屬性是顏色,數字。

#定義乙個手類,屬性是撲克牌得顏色數字

#定義乙個人類,屬性是左手,右手。類裡定義一些方法,比如交換,展示

class poker :

def __init__(self,colour ,num):

self.colour = colour

self.num = num

def __str__(self):

return "{},{}".format(self.colour,self.num)

p1 = poker("紅桃","a")

p2 = poker("黑桃","k")

#定義乙個手得類

class hand :

def __init__(self,poker):

self.poker = poker

left_hand = hand(p1)

right_hand = hand(p2)

#定義乙個人的類

class person :

def __init__(self,left_hand ,right_hand):

self.left_hand = left_hand

self.right_hand = right_hand

def show_hand(self):

print(self.right_hand.poker,self.left_hand.poker)

def swap_hand(self):

self.left_hand.poker,self.right_hand.poker = self.right_hand.poker,self.left_hand.poker

xiaoming = person(left_hand,right_hand)

xiaoming.show_hand()

xiaoming.swap_hand()

xiaoming.show_hand()

總結,裡面的變數只是乙個變數,形參是變數,物件也是變數。當你將乙個物件作為乙個引數傳入另外乙個類中的時候,才會發生關係。給大家乙個改良版的,加強大家理解。

class poker :

def __init__(self,colour ,num):

self.colour = colour

self.num = num

def __str__(self):

return "{},{}".format(self.colour,self.num)

p1 = poker("紅桃","a")

p2 = poker("黑桃","k")

#定義乙個手得類

class hand :

def __init__(self,pai):

self.paipai = pai

left_hand = hand(p1)

right_hand = hand(p2)

#定義乙個人的類

class person :

def __init__(self,bianliang ,suibian):

self.zuoshou = bianliang

self.youshou = suibian

def show_hand(self):

print(self.youshou.paipai,self.zuoshou.paipai)

def swap_hand(self):

self.zuoshou.paipai,self.youshou.paipai = self.youshou.paipai,self.zuoshou.paipai

#xiamian de left_hand riaht_hand 是hand的物件哦。

xiaoming = person(left_hand,right_hand)

xiaoming.show_hand()

xiaoming.swap_hand()

xiaoming.show_hand()

同學們仔細對比一下,仔細體會一下,就是說類的屬性,原來是空白的,只有你給她傳進去 乙個具體的之後,它才例項化。傳之前,類的屬性函式_init_裡面的引數,只是乙個變數。

python 類與物件練習題

1 建立person類,屬性有姓名 年齡 性別,建立方法personinfo,列印這個人的資訊 2 建立student類,繼承person類,屬性有學院college 班級class,重寫父類personinfo方法,呼叫父類方法列印個人資訊外,將學生的學院 班級資訊也列印出來,建立方法study引...

類與物件練習題2

1 定義乙個 book 圖書 類,在該類定義中包括資料成員 bookname 書名 price 和 number 存書 數量 count 借閱次數 成員函式 display 顯示圖書的情況 borrow 將存書數量減 1,借閱次數加 1,並顯示當前存書數量和借閱次數 restore 將存書數量加 1...

類和物件練習題

寫出乙個point 點 類,該類具有x,y 表示點的橫座標 縱座標 兩個屬性,並定義兩個構造方法,第乙個構造方法無引數,將x,y均設定為零,第二個構造方法使用座標值為引數,設定x,y為給定座標值,同時point類包含show方法,show方法可以列印輸出該類的x和y的值 實現 public clas...