|
1 | 1 | # Class and Object |
| 2 | + |
| 3 | +AIScript offers a powerful class-based object-oriented programming model inspired by Rust and JavaScript. Classes provide a clean way to encapsulate data and behavior while offering intuitive syntax for inheritance and method definition. |
| 4 | + |
| 5 | +## Defining a Class |
| 6 | + |
| 7 | +Use the `class` keyword to define a class with properties and methods: |
| 8 | + |
| 9 | +```js |
| 10 | +class Person { |
| 11 | + name: str, |
| 12 | + age: int, |
| 13 | + |
| 14 | + fn new(name: str, age: int) { |
| 15 | + self.name = name; |
| 16 | + self.age = age; |
| 17 | + } |
| 18 | + |
| 19 | + fn greet() -> str { |
| 20 | + return "Hello, my name is {self.name} and I'm {self.age} years old."; |
| 21 | + } |
| 22 | +} |
| 23 | +``` |
| 24 | + |
| 25 | +The `new` method is a special constructor that initializes a new instance of the class. |
| 26 | + |
| 27 | +## Creating Objects |
| 28 | + |
| 29 | +Create a new instance of a class using the class name followed by parentheses containing constructor arguments: |
| 30 | + |
| 31 | +```js |
| 32 | +let alice = Person("Alice", 30); |
| 33 | +print(alice.greet()); // "Hello, my name is Alice and I'm 30 years old." |
| 34 | +``` |
| 35 | + |
| 36 | +You can also use object literal syntax with type checking: |
| 37 | + |
| 38 | +```js |
| 39 | +let bob = Person { |
| 40 | + name: "Bob", |
| 41 | + age: 25, |
| 42 | +}; |
| 43 | + |
| 44 | +print(bob.greet()); // "Hello, my name is Bob and I'm 25 years old." |
| 45 | +``` |
| 46 | + |
| 47 | +## Accessing Properties and Methods |
| 48 | + |
| 49 | +Access object properties and methods using the dot notation: |
| 50 | + |
| 51 | +```js |
| 52 | +print(alice.name); // "Alice" |
| 53 | +alice.age = 31; |
| 54 | +print(alice.age); // 31 |
| 55 | +print(alice.greet()); // "Hello, my name is Alice and I'm 31 years old." |
| 56 | +``` |
| 57 | + |
| 58 | +## Field Validation |
| 59 | + |
| 60 | +AIScript supports field validation using directive annotations similar to Python's [Pydantic](https://docs.pydantic.dev/latest/): |
| 61 | + |
| 62 | +```js |
| 63 | +class User { |
| 64 | + @string(min_len=3, max_len=50) |
| 65 | + username: str, |
| 66 | + |
| 67 | + @string(pattern="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$") |
| 68 | + email: str, |
| 69 | + |
| 70 | + @number(min=0, max=120) |
| 71 | + age: int, |
| 72 | +} |
| 73 | + |
| 74 | +// This will throw a validation error |
| 75 | +let invalid_user = User { |
| 76 | + username: "a", |
| 77 | + email: "not-an-email", |
| 78 | + age: 150, |
| 79 | +} |err| { |
| 80 | + print("Validation error:", err); |
| 81 | +}; |
| 82 | +``` |
| 83 | + |
| 84 | +## Inheritance |
| 85 | + |
| 86 | +Use the parentheses syntax to inherit from another class: |
| 87 | + |
| 88 | +```js |
| 89 | +class Employee(Person) { |
| 90 | + @string |
| 91 | + job_title: str, |
| 92 | + |
| 93 | + fn new(name: str, age: int, job_title: str) { |
| 94 | + // Call the parent class constructor |
| 95 | + super.new(name, age); |
| 96 | + self.job_title = job_title; |
| 97 | + } |
| 98 | + |
| 99 | + fn greet() -> str { |
| 100 | + return "Hello, I'm {self.name}, a {self.job_title}."; |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +let developer = Employee("Carlos", 28, "Software Developer"); |
| 105 | +print(developer.greet()); // "Hello, I'm Carlos, a Software Developer." |
| 106 | +``` |
| 107 | + |
| 108 | +:::danger |
| 109 | +AIScript only support inherit single super class. |
| 110 | +::: |
| 111 | + |
| 112 | +## Default Values |
| 113 | + |
| 114 | +You can provide default values for class properties: |
| 115 | + |
| 116 | +```js |
| 117 | +class Config { |
| 118 | + host: str = "localhost", |
| 119 | + port: int = 8080, |
| 120 | + debug: bool = false, |
| 121 | + |
| 122 | + fn get_url() -> str { |
| 123 | + return "http://{self.host}:{self.port}"; |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +// Use defaults |
| 128 | +let default_config = Config(); |
| 129 | +print(default_config.get_url()); // "http://localhost:8080" |
| 130 | + |
| 131 | +// Override defaults |
| 132 | +let custom_config = Config { |
| 133 | + host: "example.com", |
| 134 | + port: 443, |
| 135 | +}; |
| 136 | +print(custom_config.get_url()); // "http://example.com:443" |
| 137 | +``` |
| 138 | + |
| 139 | +## Error Handling in Methods |
| 140 | + |
| 141 | +Methods can declare and handle errors using the same error handling syntax as regular functions: |
| 142 | + |
| 143 | +```js |
| 144 | +enum NetworkError! { |
| 145 | + ConnectionFailed, |
| 146 | + Timeout, |
| 147 | + ServerError(str), |
| 148 | +} |
| 149 | + |
| 150 | +class APIClient { |
| 151 | + base_url: str, |
| 152 | + |
| 153 | + fn new(base_url: str) { |
| 154 | + self.base_url = base_url; |
| 155 | + } |
| 156 | + |
| 157 | + fn fetch(endpoint: str) -> str | NetworkError! { |
| 158 | + if self.base_url == "" { |
| 159 | + raise NetworkError!::ServerError("Base URL is not set"); |
| 160 | + } |
| 161 | + |
| 162 | + // Simulate network request |
| 163 | + if endpoint == "/error" { |
| 164 | + raise NetworkError!::ConnectionFailed; |
| 165 | + } |
| 166 | + |
| 167 | + return "Response from {self.base_url}{endpoint}"; |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +let client = APIClient("https://api.example.com"); |
| 172 | + |
| 173 | +let result = client.fetch("/users") |err| { |
| 174 | + print("Error fetching data:", err); |
| 175 | + return "Failed to fetch"; |
| 176 | +}; |
| 177 | + |
| 178 | +print(result); // "Response from https://api.example.com/users" |
| 179 | +``` |
| 180 | + |
| 181 | +This overview covers the fundamentals of class and object-oriented programming in AIScript. By combining these features with AIScript's error handling, validation, and type system, you can create clean, maintainable, and robust code. |
0 commit comments