gpt4 book ai didi

python - 无法通过类继承正确使用另一个类的函数

转载 作者:行者123 更新时间:2023-12-01 07:40:01 25 4
gpt4 key购买 nike

我正在尝试使用 Card 类中的 card_number() 和 card_suit() 方法来确定 Rules 类中的 last_card 花色和号码

class Card:

def __init__(self, card):
self.card = card
self.number = self.card_number(card)
self.suit = self.card_suit(card)

def card_number(self, card):
card = self.card
number = card[0]
return number


def card_suit(self, card):
card = self.card
suit = card[-1]
return suit

class Rules(Card):

def __init__(self, last_card, card):
Card.__init__(self, card)
self.last_card = last_card
self.last_card_number = self.card_number(self.last_card)
self.last_card_suit = self.card_suit(self.last_card)

看起来,当我访问该功能时,他们保存卡片并仅适用于卡片变量,也在最后一张卡片中

现在我得到:

a = Rules(last_card="As", card = "5c")
print(a.card) -> "5c"
print(a.number)-> "5"
print(a.suit) -> "c"

print("last_card")
print(a.last_card) -> "As"
print(a.last_card_number) -> "5"
print(a.last_card_suit) -> "c"

我期待:

a = Rules(last_card="As", card = "5c")
print(a.card) -> "5c"
print(a.number)-> "5"
print(a.suit) -> "c"

print("last_card")
**print(a.last_card) -> "As"
print(a.last_card_number) -> "A"
print(a.last_card_suit) -> "s"**

最佳答案

正如我在评论中提到的,当您需要 Rules 来保存时,您不需要 Rules 成为 Card 的父类(super class)Card 的两个实例

您可以修改您的类来实现这一点,如下所示

class Card:

#Instantiating instance attributes
def __init__(self, card):
self.card = card
self.number = self.card[0]
self.suit = self.card[-1]

class Rules:

#Two instances of Card class
def __init__(self, last_card, card):
self.last_card = Card(last_card)
self.card = Card(card)

a = Rules(last_card="As", card = "5c")
print(a.card.card)
print(a.card.number)
print(a.card.suit)

print(a.last_card.card)
print(a.last_card.number)
print(a.last_card.suit)

输出将是

5c
5
c
As
A
s

您甚至可以摆脱 Rules 类并创建 Card 类的两个实例,然后使用它们

last_card = Card('As')
card = Card('5c')

关于python - 无法通过类继承正确使用另一个类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56767535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com