第 6 章:类与对象
self、构造、继承;日常数据用 dataclass 最省事。
01最小类
Python
class User:
def __init__(self, name: str):
self.name = name
def hello(self) -> str:
return f"hi {self.name}"
u = User("Ada")
print(u.hello())
Kotlin
class User(val name: String) {
fun hello() = "hi $name"
}
val u = User("Ada")
println(u.hello())
ArkTS
class User {
name: string;
constructor(name: string) {
this.name = name;
}
hello(): string {
return `hi ${this.name}`;
}
}
const u = new User("Ada");
console.info(u.hello());
实例方法第一参数必须写
self(名字可改但别改);调用时不用手动传。02继承
Python
class Animal:
def speak(self) -> str:
return "..."
class Dog(Animal):
def speak(self) -> str:
return "woof"
print(Dog().speak())
Kotlin
open class Animal {
open fun speak() = "..."
}
class Dog : Animal() {
override fun speak() = "woof"
}
ArkTS
class Animal {
speak(): string { return "..."; }
}
class Dog extends Animal {
speak(): string { return "woof"; }
}
03@dataclass ≈ data class
Python
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(1, 2)
print(p) # Point(x=1, y=2)
Kotlin
data class Point(val x: Int, val y: Int)
val p = Point(1, 2)
println(p)
ArkTS
// ArkTS 无内置 data class,手写字段 + 构造
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x; this.y = y;
}
}
纯数据载体优先
@dataclass;需要行为再写普通 class。04@property
Python
class Rect:
def __init__(self, w: float, h: float):
self._w, self._h = w, h
@property
def area(self) -> float:
return self._w * self._h
print(Rect(3, 4).area) # 无括号
Kotlin
class Rect(val w: Double, val h: Double) {
val area: Double get() = w * h
}
println(Rect(3.0, 4.0).area)
ArkTS
class Rect {
private w: number;
private h: number;
constructor(w: number, h: number) {
this.w = w; this.h = h;
}
get area(): number {
return this.w * this.h;
}
}