如何用Pine Script创建自定义类



是否可以在Pine中创建自定义类,以及如何创建自定义类?我在网上搜索了如何用Pine Script上课,但没有找到一个页面。

下面是一个用Python制作的类示例:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)

从v5开始,Pine Script不支持类。在Pine Script中,类型是最接近类的东西。

例如:

// @version=5
library('mylib')
// Custom types can only have attributes. No methods are allowed.
export type person        // lower first case is just a convention as seen in builtin objects
string  name
int     age
over18  boolean
bool    isVip = false // Only constant literals, no expressions historical access allowed in default value.
export new(string name, int age) =>
isOver18 = age >= 18
person   = person.new(name, age, isOver18)
person

您可以在发布库后按如下方式使用它。(你不必把它变成一个库,你可以把它添加到你的代码中,但当它用作库时,它更接近于一个类。(

import your_username/mylib/1
// Create with our factory/constructor
john         = mylib.new("John", 25)
isJohnOver18 = john.over18                  // true
// Unfortunately there is nothing to prevent direct object creation
mike         = mylib.person.new("Mike", 25) // Create object with type's builtin constructor.
isMikeOver18 = mike.over18                  // na

编辑:我目前看到了奇怪的行为,我无法理解使用类型化参数和访问其历史值的原因。参见以下示例:


weirdFunction(person user) =>
// This is somehow not working as expected in the function.
// However it works flawlessly in a global context.
previousAge = user.age[1] // Gets wrong value
// Workaround
correctFunction(person user) =>
previousUser = user[1]
previousAge = previousUser.age

不,Pine Script的设计并没有使用面向对象编程和类支持的概念。

最新更新