Is it possible to instantiate an object of one class in two different ways?

青春壹個敷衍的年華 提交于 2019-12-11 00:02:11

问题


Here is an example which creates a point as p=Point(x, y). Assume that I have some array ppp=(x, y) where x and y are numbers and I want to make it of class Point but in the way: p=Point(ppp). I can do either one or another way but not both simultaneously. Is it possible to have both ways?


回答1:


If you know that you have a tuple/list while creating the instance, you can do: p = Point(*ppp), where ppp is the tuple.




回答2:


There are two different ways to acquire the result, the first is to analyse arguments that you pass to __init__ and in dependence of their quantity and type - choose a decision what are you using to instantiate class.

class Point(object):

    x = 0
    y = 0

    def __init__(self, x, y=None):
       if y is None:
           self.x, self.y = x, x
       else:
           self.x, self.y = x, y

The other decision is to use classmethods as instantiators:

class Point(object):

    x = 0
    y = 0

    @classmethod
    def from_coords(cls, x, y):
       inst = cls()
       inst.x = x
       inst.y = y
       return inst

    @classmethod
    def from_string(cls, x):
       inst = cls()
       inst.x, inst.y = x, x
       return inst

p1 = Point.from_string('1.2 4.6')
p2 = Point.from_coords(1.2, 4.6)



回答3:


class Point:
    def __init__(self, x, y=None):
        if isinstance(x, tuple):
            self.x, self.y = x
         else:
            self.x = x
            self.y = y



回答4:


Yes:

class Point(object):
    def __init__(self, x, y=None):
        if y is not None:
            self.x, self.y = x, y
        else:
            self.x, self.y = x

    def __str__(self):
        return "{}, {}".format(self.x, self.y)

print Point(1,2)
# 1, 2
print Point((1,2))
# 1, 2



回答5:


I would guess that your looking for a way to overload your constructor, as is common in statically typed languages such as C++ and Java.

This is not possible in Python. What you can do is provide different keyword argument combinations, something like:

class Point(object):
  def __init__(self, x=None, y=None, r=None, t=None):
    if x is not None and y is not None:
      self.x = x
      self.y = y
    elif r is not None and t is not None:
      # set cartesian coordinates from polar ones

Which you would then use as:

p1 = Point(x=1, y=2)
p2 = Point(r=1, t=3.14)


来源:https://stackoverflow.com/questions/11899959/is-it-possible-to-instantiate-an-object-of-one-class-in-two-different-ways

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!