用Python设置例子进行同步赋值、封装与结构
同步赋值示例:
a, b, c = 1, 2, 3
print(a, b, c) # 输出结果:1 2 3
封装示例:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name: {self.name}, Age: {self.age}"
person = Person("Alice", 25)
print(person) # 输出结果:Name: Alice, Age: 25
结构示例:
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to_origin(self):
return math.sqrt(self.x ** 2 + self.y ** 2)
def __str__(self):
return f"({self.x}, {self.y})"
p = Point(3, 4)
print(p) # 输出结果:(3, 4)
print(p.distance_to_origin()) # 输出结果:5.0
原文地址: https://www.cveoy.top/t/topic/bW0J 著作权归作者所有。请勿转载和采集!