0

我在 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_tripletsDict应该let_set采取什么形式?

4

1 回答 1

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)

The methods can then expect to operate on those classes appropriately to access the attributes. This example is not specifically checking the capabilities of the objects being passed in, but they would obviously raise an exception when you try to access an improper object type that does not have a .string or .let_set attribute.

于 2012-10-10T20:35:26.313 回答