Is it possible to instantiate an object of one cla

2019-07-22 03:26发布

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?

5条回答
做自己的国王
2楼-- · 2019-07-22 03:47

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

查看更多
forever°为你锁心
3楼-- · 2019-07-22 03:47

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)
查看更多
Juvenile、少年°
4楼-- · 2019-07-22 03:49

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)
查看更多
Viruses.
5楼-- · 2019-07-22 04:00

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
查看更多
贼婆χ
6楼-- · 2019-07-22 04:02
class Point:
    def __init__(self, x, y=None):
        if isinstance(x, tuple):
            self.x, self.y = x
         else:
            self.x = x
            self.y = y
查看更多
登录 后发表回答