【问题标题】:__init__ Constructor in Python__init__ Python 中的构造函数
【发布时间】:2015-04-25 21:56:48
【问题描述】:

我正在尝试为“块”类编写一个构造函数,该类存储块中心的坐标(作为单独的 x 和 y 坐标或一对数字)以及宽度和高度块。我遇到的问题是编写一个 init,它可以为 x,y 获取坐标元组,也可以为 x 和 y 获取单个数字。

这是我目前所拥有的:

 def __init__(self,(x,y),height,width):

【问题讨论】:

  • 否则您可以为每个以0 作为默认值的参数设置默认参数。
  • 你能不能不限制输入到一个或另一个?
  • 注意:在 python3 中,参数列表中不能有元组。在python中你确实可以做def f((x,y)):,但在python3你必须做def f(x_y): x,y = x_y才能达到同样的效果。

标签: python class constructor tuples init


【解决方案1】:

使用关键字参数:

class Blocks(object):
    def __init__(self, center=None, x=None, y=None, height=0, width=0):
        if center is None:
            # x and y must be set
            if x is None or y is None:
                raise TypeError('You must either specify a center or both x and y')
        else:
            # center is set, so x and y must not be
            if x is not None or y is not None:
                raise TypeError('You must either specify a center or both x and y')
            x, y = center
        # here you always have x and y set

现在您可以使用Blocks(center=(10, 20)),也可以使用Blocks(x=10, y=20)。高度和宽度有默认值,但可以被覆盖。

另一种方法是使用类方法:

class Blocks(object):
    def __init__(self, x, y, height, width):
        # here you always have x and y set

    @classmethod
    def from_center(cls, center, height, width):
        x, y = center
        return cls(x, y, height, width)

并使用任一:

block_one = Block(10, 20, 5, 5)

或

block_two = Block.from_center((10, 20), 5, 5)

【讨论】:

  • 如果用户同时通过会发生什么?
  • @PadraicCunningham:构造函数中的错误处理,已添加。
  • 加 1 但这不漂亮!
【解决方案2】:

您可以使用一些默认参数并根据填充的参数决定使用哪个:

class Block(object):

    def __init__(self, height, width, coord_tuple=None, coord_x=None, coord_y=None):

        if coord_tuple:
            self.x = coord_tuple[0]
            self.y = coord_tuple[1]
        else:
            self.x = coord_x
            self.y = coord_y

        self.height = height
        self.width = width

        return

    def print_coord(self):
        print("Height: {}\nWidth: {}\nX: {}\nY: {}"
                .format(self.height, self.width, self.x, self.y))
        return

# tuple instantiations 
b1 = Block(1, 2, (1,2))
b2 = Block(3, 4, coord_tuple=(3,4))

# x/y instantiation
b3 = Block(5, 6, coord_x=5,coord_y=6)

b1.print_coord()
b2.print_coord()
b3.print_coord()

生产:

身高:1
宽度:2
X: 1
Y:2
身高:3
宽度:4
X:3
Y: 4
身高:5
宽度:6
X: 5
是:6

【讨论】:

    【解决方案3】:

    您可以使用可变数量的参数:

    class Block(object):
        def __init__(self, center, *args):
            if isinstance(center, tuple) and args and len(args) > 1:
                self.x, self.y = center
                self.w, self.h = args[:2]
            elif args and len(args) > 2:
                self.x = center
                self.y = args[0]
                self.w, self.h = args[1:3]
            else:
                raise Exception('Some exception')
    
    b1 = Block(1, 1, 10, 10)
    b2 = Block((2, 2), 10, 10)
    

    【讨论】:

      猜你喜欢
      • 2012-02-17
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      相关资源
      最近更新 更多