としてポイントを作成する例を次に示しますp=Point(x, y)
。とが数字である配列ppp=(x, y)
があり、それをクラスにしたいのですが、途中で:と仮定します。いずれかの方法で行うことはできますが、両方を同時に行うことはできません。両方の方法を持つことは可能ですか?x
y
Point
p=Point(ppp)
5 に答える
3
結果を取得するには 2 つの異なる方法があります。1 つ目は、__init__ に渡す引数を分析し、その量と型に応じて、クラスのインスタンス化に使用するものを決定することです。
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
もう 1 つの決定は、クラスメソッドをインスタンス化子として使用することです。
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)
于 2012-08-10T10:50:32.183 に答える
2
インスタンスの作成中にタプル/リストがあることがわかっている場合はp = Point(*ppp)
、次のことができますppp
。
于 2012-08-10T11:07:18.887 に答える
0
class Point:
def __init__(self, x, y=None):
if isinstance(x, tuple):
self.x, self.y = x
else:
self.x = x
self.y = y
于 2012-08-10T10:46:21.280 に答える
0
はい:
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
于 2012-08-10T10:46:23.170 に答える
-1
C++ や Java などの静的に型付けされた言語で一般的であるように、コンストラクターをオーバーロードする方法を探していると思います。
これは Python では不可能です。できることは、次のようなさまざまなキーワード引数の組み合わせを提供することです。
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
次に、次のように使用します。
p1 = Point(x=1, y=2)
p2 = Point(r=1, t=3.14)
于 2012-08-10T10:56:08.673 に答える