【问题标题】:Classes in GenieGenie 中的课程
【发布时间】:2016-01-15 06:10:49
【问题描述】:

我正在尝试在 Genie 中为 python 复制 Verbal Expression 库,作为学习如何使用类的练习。我有一些简单的类,就像教程中列出的那些,但是当涉及到以面向对象的方式实例化方法时,我遇到了问题。这是我正在尝试的:

出于培训目的,我想要一个名为 add 的方法,其行为与 string.concat() 相同。

[indent=4]
class VerEx : Object
    def add(strg:string) : string
        return this.concat(strg)

但我得到了错误:

verbalexpressions.gs:33.16-33.26: error: The name `concat' does not exist in the context of `VerEx'

当我使用不同的方法时,例如:

class VerEx : Object
def add(strg:string) : string
    a:string=""
    a.concat(strg)
    return a

init
    test:string = "test"
    sec:string = " + a bit more"
    print test.VerEx.add(sec)

我在上述文本的最后一行收到错误,并带有警告:

verbalexpressions.gs:84.11-84.21: error: The name `VerEx' does not exist in the context of `string?'

我希望能够使 test.add(sec) 的行为与 test.concat(sec) 相同,我该怎么做才能做到这一点?

【问题讨论】:

    标签: genie


    【解决方案1】:

    一个小例子, 笔记: 在

    中取消处理RegexError
    1. 新的正则表达式
    2. r.replace

    [缩进=4]

    class VerX
        s: GenericArray of string
    
        construct ()
            s = new GenericArray of string
    
        def add (v: string): VerX
            s.add (v)
            return self
    
        def find (v: string): VerX
            return self.add ("(%s)".printf (v))
    
        def replace(old: string, repl: string): string
            // new Regex: unhandle RegexError HERE!!
            var r = new Regex (@"$(self)")
            // r.replace: unhandle RegexError HERE!!
            return r.replace(old, old.length, 0, repl)
    
        def to_string (): string
            return string.joinv ("", s.data)
    
    init
        var replace_me = "Replace bird with a duck"
        var v = new VerX
        print v.find("bird").replace(replace_me, "duck")
    
        var result = (new VerX).find("red").replace("We have a red house", "blue")
        print result
    

    【讨论】:

    • 谢谢,Zee。一个问题,为什么需要to_string呢?
    • 您好,如果一个类实现 to_string 方法,它将支持字符串插值。这里@"$(self)" 是一个字符串。但实际上它是不需要的。你可以这样写:var join = string.joinv ("", s.data); var r = new Regex (join),或var r = new Regex (string.joinv ("", s.data))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多