__init__ Python中的构造函数

时间:2015-04-25 21:56:49

标签: python class constructor tuples init

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

这是我到目前为止所做的:

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

3 个答案:

答案 0 :(得分:2)

使用关键字参数:

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)

答案 1 :(得分:0)

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

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
  Y:6

答案 2 :(得分:0)

你可以使用可变数量的args:

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)