python--初始化 print(rect.width) # 输出: 5print(rect.height) # 输出: 10print(rect.area) # 输出: 50。
init实现初始化的情况
1.基本初始化方法
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
print(person.name) # 输出: Alice
print(person.age) # 输出: 30
2.默认参数
class Car:
def __init__(self, make, model, year=2023):
self.make = make
self.model = model
self.year = year
car = Car("Toyota", "Camry")
print(car.make) # 输出: Toyota
print(car.model) # 输出: Camry
print(car.year) # 输出: 2023
3.调用父类初始化方法
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
student = Student("Bob", 20, "S12345")
print(student.name) # 输出: Bob
print(student.age) # 输出: 20
print(student.student_id) # 输出: S12345
4.多重继承
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Worker:
def __init__(self, job_title):
self.job_title = job_title
class Employee(Person, Worker):
def __init__(self, name, age, job_title):
Person.__init__(self, name, age)
Worker.__init__(self, job_title)
employee = Employee("Charlie", 25, "Developer")
print(employee.name) # 输出: Charlie
print(employee.age) # 输出: 25
print(employee.job_title) # 输出: Developer
5.自定义初始化方法
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
self.area = width * height
rect = Rectangle(5, 10)
print(rect.width) # 输出: 5
print(rect.height) # 输出: 10
print(rect.area) # 输出: 50
6.初始化方法中的条件判断
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
self.discount = 0.1 if price > 100 else 0.0
product1 = Product("Laptop", 1200)
print(product1.name) # 输出: Laptop
print(product1.price) # 输出: 1200
print(product1.discount) # 输出: 0.1
product2 = Product("Book", 50)
print(product2.name) # 输出: Book
print(product2.price) # 输出: 50
print(product2.discount) # 输出: 0.0
7.初始化方法中的异常处理
class BankAccount:
def __init__(self, account_number, balance):
if balance < 0:
raise ValueError("Balance cannot be negative")
self.account_number = account_number
self.balance = balance
try:
account1 = BankAccount("123456", 1000)
print(account1.account_number) # 输出: 123456
print(account1.balance) # 输出: 1000
account2 = BankAccount("654321", -500)
except ValueError as e:
print(e) # 输出: Balance cannot be negative
其他初始化的情况
在 Python 中,除了 init 方法用于对象的初始化外,还有一些其他特殊方法和技巧可以用于对象的初始化或配置。以下是一些常见的初始化方法和技巧。
1.__new__方法
作用:new 方法是 Python 中用于创建对象实例的静态方法。它在 init 方法之前被调用。
使用场景:通常用于创建不可变对象(如 int、str、tuple)或实现单例模式。
实现单例模式的中心思想就是:在类中定义一个标识 _instance,用于记录是否已经创建了实例。如果是第一次创建实例,则创建一个新的实例并将其赋值给 _instance,否则直接返回已经存在的实例。
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, value):
self.value = value
# 创建两个 Singleton 对象
s1 = Singleton(10)
s2 = Singleton(20)
print(s1.value) # 输出: 20
print(s2.value) # 输出: 20
print(s1 is s2) # 输出: True
2.类方法(@classmethod)
作用:类方法可以用于创建对象实例,通常用于工厂模式。
使用场景:当你需要根据不同的参数创建不同的对象实例时,可以使用类方法。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_birth_year(cls, name, birth_year):
age = 2023 - birth_year
return cls(name, age)
# 使用类方法创建 Person 对象
person = Person.from_birth_year("Alice", 1990)
print(person.name) # 输出: Alice
print(person.age) # 输出: 33
3.静态方法(@staticmethod)
静态方法不依赖于类的实例或类本身
作用:静态方法不依赖于类的实例,通常用于与类相关的辅助函数。
使用场景:当你有一些与类相关的逻辑,但不需要访问类的实例或类本身时,可以使用静态方法。
class MathUtils:
@staticmethod
def add(a, b):
return a + b
# 使用静态方法
result = MathUtils.add(5, 10)
print(result) # 输出: 15
4.属性装饰器(@property)
作用:属性装饰器用于将方法转换为属性,方便访问和修改对象的属性。
使用场景:当你需要对属性的访问和修改进行控制时,可以使用属性装饰器。
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
# 创建 Circle 对象
circle = Circle(5)
print(circle.radius) # 输出: 5
circle.radius = 10
print(circle.radius) # 输出: 10
try:
circle.radius = -5
except ValueError as e:
print(e) # 输出: Radius cannot be negative
5.工厂函数
作用:工厂函数用于创建对象实例,通常用于封装对象的创建逻辑。
使用场景:当你需要根据不同的条件创建不同的对象实例时,可以使用工厂函数。
def create_person(name, age, is_student=False):
if is_student:
return Student(name, age)
else:
return Person(name, age)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Student(Person):
def __init__(self, name, age):
super().__init__(name, age)
self.student_id = "S12345"
# 使用工厂函数创建对象
person = create_person("Alice", 30)
print(person.name) # 输出: Alice
print(person.age) # 输出: 30
student = create_person("Bob", 20, is_student=True)
print(student.name) # 输出: Bob
print(student.age) # 输出: 20
print(student.student_id) # 输出: S12345
6.pydantic
自动生成:pydantic 会自动生成一个构造函数 init,用于初始化对象。
class KgInfoCollection(BaseModel) 在使用 pydantic 库时。通过继承 BaseModel,你可以定义具有类型注解和验证功能的数据模型类。pydantic 会自动生成构造函数,用于初始化对象,并进行类型验证和默认值处理
from pydantic import BaseModel
from typing import Optional
class KgInfoCollection(BaseModel):
"""
Kg Store collection
"""
name: str
dimension: Optional[int] = None
fields_schema: Optional[dict] = None
metric: Optional[str] = None
# 创建一个 KgInfoCollection 对象
kg_info = KgInfoCollection(name="example", dimension=10, fields_schema={"key": "value"}, metric="cosine")
# 打印对象
print(kg_info)
# 序列化为 JSON
print(kg_info.json())
python--初始化 print(rect.width) # 输出: 5print(rect.height) # 输出: 10print(rect.area) # 输出: 50。python--初始化 print(rect.width) # 输出: 5print(rect.height) # 输出: 10print(rect.area) # 输出: 50。python--初始化 print(rect.width) # 输出: 5print(rect.height) # 输出: 10print(rect.area) # 输出: 50。python--初始化 print(rect.width) # 输出: 5print(rect.height) # 输出: 10print(rect.area) # 输出: 50。python--初始化 print(rect.width) # 输出: 5print(rect.height) # 输出: 10print(rect.area) # 输出: 50。python--初始化 print(rect.width) # 输出: 5print(rect.height) # 输出: 10print(rect.area) # 输出: 50。python--初始化 print(rect.width) # 输出: 5print(rect.height) # 输出: 10print(rect.area) # 输出: 50。python--初始化 print(rect.width) # 输出: 5print(rect.height) # 输出: 10print(rect.area) # 输出: 50。python--初始化 print(rect.width) # 输出: 5print(rect.height) # 输出: 10print(rect.area) # 输出: 50。