我目前正在學習 Python 教程,在觀看了有關創建類和定義其方法的課程后,我想知道是否可以組合方法。
所以不要使用:
class Coordinates:
def point1(self):
print(x)
def point2(self):
print(y)
def point3(self):
print(z)
x = 5
y = 4
z = 9
Coordinates.point1(x) / Coordinates.point2(y) / Coordinates.point3(z)
我可以改為使用它來呼叫 x、y 或 z:
class Coordinates:
def point(self):
print(x or y or z)
x = 5
y = 4
z = 9
Coordinates.point(x/y/z)
如果我這樣做,盡管我總是在終端上得到 x 的數字 5,無論我是否使用 x、y 或 z 作為 self。
感謝您的任何輸入:)
uj5u.com熱心網友回復:
您不需要單獨的函式來獲取每個 x、y 和 z 值。
首先,您可以通過直接訪問這樣的實體變數來考慮根本沒有函式:
class Coordinates:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
C = Coordinates(10, 20, 30)
print(C.x, C.y, C.z)
另一種選擇是使用屬性。例如:
class Coordinates:
def __init__(self, x, y, z):
self._x = x
self._y = y
self._z = z
@property
def x(self):
return self._x
@property
def y(self):
return self._y
@property
def z(self):
return self._z
C = Coordinates(10, 20, 30)
print(C.x, C.y, C.z)
通過這種方式,您可以控制任何給定值的回傳值。
你甚至可以讓你的類表現得像一個字典,如下所示:
class Coordinates:
def __init__(self, x, y, z):
self.d = {'x': x, 'y': y, 'z': z}
def __getitem__(self, k):
return self.d.get(k, None)
C = Coordinates(10, 20, 30)
print(C['x'], C['y'], C['z'])
在最后一個示例中,您只有一個函式涉及獲取變數,但即便如此,您也沒有顯式呼叫它
uj5u.com熱心網友回復:
class Coordinates:
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
def point(self,letter):
if letter == "x" :
print(self.x)
elif letter == "y" :
print(self.y)
elif letter == "z":
print(self.z)
cord= Coordinates(5,4,9)
cord.point('x')
uj5u.com熱心網友回復:
據我了解,您想從Class呼叫單個方法,該方法應根據指定的輸入 [x 或 y 或 z] 執行條件,而不是為這些方法設定單獨的方法。
如果是這種情況,您可以閱讀下文了解如何操作
class Coordinates:
def __init__(self,x,y,z):
self.x_value = x # Holds the value of x coordinate when initializing the class
self.y_valye = y # Holds the value of y ...
self.z_value = z # Holds the value of z ...
# The match case is only available in python 3.10 [ you can use simple if else statements instead for below versions ]
def eval_point(self,coordinate_axis):
match coordinate_axis:
case "x":
print("Eval x coordinate function here")
case "y":
print("Eval y coordinate function here")
case "z":
print("Eval z coordinate function here")
x = 5
y = 4
z = 9
eval_coordinate = Coordinates(x,y,z) # Values should be passed in order as defined in constructor
eval_coordinate.eval_point("x") # Change the string value to whatever coordinate eval you want [example x,y,z]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/416014.html
標籤:
上一篇:使用帶輸入的類連接實體屬性
下一篇:Swift類繼承初始化程式錯誤
