我在Python中有以下类:
class String:
def clean_string(self, corpus):
f = open(corpus, 'r')
raw = f.read().lower()
f.close()
raw1 = re.sub(omissis, '', raw)
self.string = raw1
def print_string(self):
return self.string
class Set:
def letters_set(self, string):
self.let_set = set(re.findall(omissis, string))
class Dict:
def __init__(self, dictionary={}):
self.dictionary = {}
self.string = String()
self.let_set = Set()
def generate_possible_triplets(self, let_set):
triplet = [(ch1, ch2, ch3) for ch1 in let_set
for ch2 in let_set
for ch3 in let_set]
[...]
我将对象作为函数参数出现问题。假设我想要创建类Set
的一个实例,类String
之一,并调用方法.letters_set(String.string)
。
我必须把什么作为参数放在括号内?我将创建的类字符串对象的名称?引用此对象的变量? (同样适用于.generate_possible_triplets
中的Dict
方法。let_set
应采用什么形式?
答案 0 :(得分:1)
您可能只想让您的方法接受自定义类的实例......
class String:
...
class Set:
def letters_set(self, stringObj):
# stringObj is a String instance
self.let_set = set(re.findall(omissis, stringObj.string))
class Dict:
...
def generate_possible_triplets(self, setObj):
# setObj is a Set instance
triplet = [(ch1, ch2, ch3) for ch1 in setObj.let_set
for ch2 in setObj.let_set
for ch3 in setObj.let_set]
aString = String()
aSet = Set()
aDict = Dict()
aSet.letters_set(aString)
aDict.generate_possible_triplets(aSet)
然后,这些方法可以适当地对这些类进行操作以访问属性。此示例并未专门检查传入的对象的功能,但当您尝试访问不具有.string
或.let_set
属性的不正确对象类型时,它们显然会引发异常。 / p>