init 方法用于在创建对象时自动初始化属性,如设置 name 和 age;它可验证参数、设默认值,并通过 super() 调用父类初始化方法,确保对象创建后立即具备初始状态。

__init__
__init__
__init__
想象一下,你要创建一个
Person
__init__
Person
__init__
例如:
立即学习“Python免费学习笔记(深入)”;
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
print(person1.greet()) # 输出: Hello, my name is Alice and I am 30 years old.
print(person2.greet()) # 输出: Hello, my name is Bob and I am 25 years old.
在这个例子中,
__init__
name
age
self.name
self.age
Person
__init__
__init__
self
self
__init__
参数可以有默认值,也可以是可选的。例如:
class Rectangle:
def __init__(self, width, height=10):
self.width = width
self.height = height
def area(self):
return self.width * self.height
rect1 = Rectangle(5) # height 使用默认值 10
rect2 = Rectangle(5, 20) # height 显式设置为 20
print(rect1.area()) # 输出: 50
print(rect2.area()) # 输出: 100这里,
height
Rectangle
height
__init__
__init__
例如:
立即学习“Python免费学习笔记(深入)”;
class Circle:
def __init__(self, radius):
if radius <= 0:
raise ValueError("Radius must be positive")
self.radius = radius
self.area = 3.14159 * radius * radius
def describe(self):
return f"Circle with radius {self.radius} and area {self.area}"
try:
circle1 = Circle(-5) # 抛出 ValueError
except ValueError as e:
print(e) # 输出: Radius must be positive
circle2 = Circle(3)
print(circle2.describe()) # 输出: Circle with radius 3 and area 28.27431在这个例子中,
__init__
radius
ValueError
self.area
__init__
__new__
__init__
__new__
__new__
通常情况下,你不需要重写
__new__
例如:
立即学习“Python免费学习笔记(深入)”;
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self, name):
self.name = name
s1 = Singleton("First")
s2 = Singleton("Second")
print(s1.name) # 输出: First
print(s2.name) # 输出: First (因为 s1 和 s2 是同一个实例)
print(s1 is s2) # 输出: True在这个例子中,
__new__
Singleton
Singleton()
__init__
__init__
如果你的类没有定义
__init__
__init__
__init__
例如:
立即学习“Python免费学习笔记(深入)”;
class Animal:
def speak(self):
print("Generic animal sound")
class Dog(Animal):
def speak(self):
print("Woof!")
dog = Dog()
dog.speak() # 输出: Woof!在这个例子中,
Dog
__init__
Animal
speak
Dog
speak
__init__
如果你在子类中定义了
__init__
__init__
super()
例如:
立即学习“Python免费学习笔记(深入)”;
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def describe(self):
return f"Vehicle: {self.make} {self.model}"
class Car(Vehicle):
def __init__(self, make, model, num_doors):
super().__init__(make, model)
self.num_doors = num_doors
def describe(self):
return f"{super().describe()}, {self.num_doors} doors"
car = Car("Toyota", "Camry", 4)
print(car.describe()) # 输出: Vehicle: Toyota Camry, 4 doors在这个例子中,
Car
__init__
super().__init__(make, model)
Vehicle
__init__
make
model
num_doors
以上就是python中__init__方法是做什么的_Python类中__init__构造方法详解的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号