答案:Python中通过__init__方法初始化类实例,self指代当前对象,可设默认参数并用于属性赋值,如Student类示例所示,注意其为初始化而非构造方法。

在 Python 中,定义类的初始化方法是通过 __init__ 方法实现的。这个方法在创建类的实例时自动调用,用来初始化对象的属性。
def __init__(self, 参数1, 参数2, ...):
self.属性1 = 参数1
self.属性2 = 参数2
下面是一个定义学生类的例子:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
立即学习“Python免费学习笔记(深入)”;
创建实例时传入对应参数:stu = Student("小明", 15)
print(stu.name) # 输出:小明
print(stu.age) # 输出:15
class Car:
def __init__(self, brand, color="白色"):
self.brand = brand
self.color = color
car1 = Car("丰田")
print(car1.color) # 输出:白色
基本上就这些,掌握 __init__ 是面向对象编程的基础。
以上就是python定义类的初始化方法的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号