iT邦幫忙

0

python casting 一問

  • 分享至 

  • xImage

大家好, 想問一下在python 可以像java 一樣做class type casting 嗎, 可以怎樣用python 表示?
dcdf = (DCDF_120)arr.get(i);
DCDF_120 是下面code的child class, DCD 是parent class, getCutOffTime 是DCD的class method,
找了好久都找不到方法, 只是看見有人說decorator , 但不太懂, 希望大家幫忙. 謝謝.

public static Date getCutOffTime(ArrayList arr)
	{
		DCDF_120 dcdf = null;
		Date t = null;
		Date tmp = null;
		
		for (int i = 0; i < arr.size(); ++i)
		{
			dcdf = (DCDF_120)arr.get(i);
			tmp = dcdf.getIntime2();
			if (t == null || (tmp != null && tmp.after(t))) t = tmp;
		}
		
		return t;
	}
rofellos iT邦新手 2 級 ‧ 2022-03-16 18:00:58 檢舉
dcdf = arr[i]
froce iT邦大師 1 級 ‧ 2022-03-16 22:31:32 檢舉
我覺得你順便把這程式要做啥說出來比較好...
用python完全硬翻java有點不太實際。

回到原題,我不知道你arr裡面裝什麼,如果一定可以轉換成dcdf
那就 dcdf = DCDF_120(arr[i]) 應該就可以了
diu7me iT邦新手 4 級 ‧ 2022-03-17 09:04:16 檢舉
謝謝你froce
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
I code so I am
iT邦高手 1 級 ‧ 2022-03-17 09:19:01

直接改變物件的 class 屬性即可。完整範例如下:

class Car:
    def __init__(self, wheels=4):
        self.wheels = wheels

    def __repr__(self):
        return 'I\'m a car.'

# Bus 繼承 Car,且多一個 get_wheels method
class Bus(Car):
    def __init__(self, wheels=4):
        super().__init__(wheels)

    def __repr__(self):
        return 'I\'m a bus.'

    def get_wheels(self):
        return self.wheels

arr = [Car(x) for x in range(10)]

print(arr[0].wheels)

# casting
arr[0].__class__ = Bus 
print(arr[0].get_wheels())

實際專案開發可考慮使用『工廠模式』,可參閱【Day 08】工廠方法設計模式(Python)

我要發表回答

立即登入回答