Skip to content

Instantly share code, notes, and snippets.

@MagicSword
Last active April 19, 2018 12:37
Show Gist options
  • Select an option

  • Save MagicSword/48e3d68a23ec6025da9b9c6464e36f70 to your computer and use it in GitHub Desktop.

Select an option

Save MagicSword/48e3d68a23ec6025da9b9c6464e36f70 to your computer and use it in GitHub Desktop.
利用動態繼承將字串數字轉換成國字 by froce

利用動態繼承將字串數字轉換成國字 by froce

看了這篇手癢,也來寫寫看。 順便練習python的物件導向。(因為我很少用) 目標,將一個字串轉換成 Hans 物件,利用 hans 屬性存取,將字串中的數字轉成正楷國字,並保有 str 的方法。

# Hans物件,繼承str,並初始化。
class Hans(str):
	def __init__(self, string=""):
		super().__init__()


# 要動態增加的方法
def hans(string):
	import re
	h = ["零", "壹", "貳", "參", "肆", "伍", "陸", "柒", "捌", "玖"]
	for i in re.findall(r"\d", string):
		string = string.replace(i, h[int(i)])
	return string
# 將 hans 屬性化,並動態增加至 Hans
Hans.hans = property(hans)
# 輸出為「EEE測試壹貳參」,可以看到可以使用了 str 的內建方法 upper()
print(Hans("eee測試123").hans.upper())
# 附記:python內建物件不可以附加方法,所以不能用

str.hans = property(hans)
# 會報錯
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment