Python:多个单参数构造函数

时间:2018-03-25 22:42:24

标签: python

我有一个Game类,其字段是Board个对象。我目前通过传递有关游戏的字符串编码信息并制作Game对象来制作Board

但是,我现在有一堆Board个对象,想要创建一个直接接收Board对象的新构造函数。

这是我当前的构造函数:

def __init__(self, game_string):
    self.single_list = game_string.split(",")
    self.board = self.parse_game_string(game_string)
    self.directions = self.get_all_directions()
    self.red_number_of_streaks = self.get_number_of_streaks("R")
    self.black_number_of_streaks = self.get_number_of_streaks("B")

但现在我有了板子对象,所以我想做:

def __init__(self, board):
    self.board = board
    self.directions = self.get_all_directions()
    self.red_number_of_streaks = self.get_number_of_streaks("R")
    self.black_number_of_streaks = self.get_number_of_streaks("B")

我不认为Python会知道如何区分这两个构造函数。我可以根据参数的类型确定要做什么?类似的东西:

如果isinstance(str):     #通常的构造函数 elif isinstance(游戏):     #new构造函数

有更好的方法吗?

谢谢!

3 个答案:

答案 0 :(得分:4)

我会这样做:

class Game:
    def __init__(self, board):
        ...

    @classmethod
    def from_string(cls, game_string):
        board = cls.parse_game_string(game_string)
        game = cls(board)
        game.something = 5

        return game

    @staticmethod
    def parse_game_string(game_string):
        ...

        return Board(...)

Game.from_string然后使用默认的Game初始化程序从字符串构造Game的实例,该初始化程序接受Board对象。

您必须使Game.parse_game_string成为静态方法,才能从Game.from_string类方法中使用它。

答案 1 :(得分:3)

查看输入类型当然是一种选择:

class Game(object):
    def __init__(self, str_or_board):
        if isinstance(str_or_board, Board):
            board = str_or_board
        else:
            board = self.parse_game_string(str_or_board)

        self.board = board

而不是isinstanceduck typing也是一种选择。

或者,您可以使用工厂功能:

class Game(object):
    def __init__(self, board):
        assert isinstance(board, Board)
        self.board = board

    @classmethod
    def fromstring(cls, board_str):
        return cls(self.parse_game_string(board_str))

# Use like ...
game1 = Game(Board())
game2 = Game.fromstring('foobar')

答案 2 :(得分:2)

对于Python中的方法重载,您可以将两个参数(<?xml version="1.0" encoding="utf-8"?> <edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx"> <edmx:DataServices> <Schema Namespace="Entities.Models" xmlns="http://docs.oasis-open.org/odata/ns/edm"> <EntityType Name="Skill"> <Key> <PropertyRef Name="Id" /> </Key> <Property Name="Id" Type="Edm.Int32" Nullable="false" /> <Property Name="Name" Type="Edm.String" /> <NavigationProperty Name="RequestNegotiations" Type="Collection(Entities.Models.RequestNegotiation)" /> <NavigationProperty Name="UserSkills" Type="Collection(Entities.Models.UserSkill)" /> </EntityType> <EntityType Name="Conversation"> <Key> <PropertyRef Name="Id" /> </Key> <Property Name="Id" Type="Edm.Int32" Nullable="false" /> <Property Name="Created" Type="Edm.DateTimeOffset" Nullable="false" /> <NavigationProperty Name="ConversationSubscriptions" Type="Collection(Entities.Models.ConversationSubscription)" /> <NavigationProperty Name="Messages" Type="Collection(Entities.Models.Message)" /> <NavigationProperty Name="ServiceRequests" Type="Collection(Entities.Models.ServiceRequest)" /> </EntityType> game_string)传递给board,将它们初始化为None。

然后你可以有一个构造函数,如:

__init__

如果提供def __init__(self, game_string=None, board=None): self.single_list = game_string.split(",") self.board = self.parse_game_string(game_string) if game_string else board self.directions = self.get_all_directions() self.red_number_of_streaks = self.get_number_of_streaks("R") self.black_number_of_streaks = self.get_number_of_streaks("B") ,它将用作董事会。否则,将使用game_string参数。