Python 面向对象编程基础

前言 Python 里"一切皆对象",但很多同学写脚本一直用不上自定义类。这篇把 OOP 核心概念讲到位,同时告诉你 Pythonic 的取舍——不为了面向对象而面向对象。 ...

2024-02-17 · 3 min · zy

Golang 结构体、方法与接口

前言 Go 没有 class、没有继承,但通过结构体 + 方法 + 接口实现了更轻量的面向对象。核心哲学一句话:组合优于继承,隐式优于显式。 一、结构体 type Server struct { Host string // 大写开头 = 导出(公开) Port int // 小写 = 包内私有 Tags []string metadata map[string]string } // 字面量初始化(推荐: 带字段名, 可读性好且不怕字段调整) s := Server{ Host: "10.0.0.1", Port: 8080, Tags: []string{"prod", "web"}, } // 零值可用(Go 设计哲学!) var s2 Server // Host="" Port=0 Tags=nil, 直接用不会崩 s2.Port = 9090 // 结构体是值类型:赋值即拷贝 s3 := s2 s3.Port = 1000 fmt.Println(s2.Port) // 9090, 不受影响 构造函数惯例(Go 没有 constructor,用普通函数模拟): ...

2024-01-20 · 3 min · zy