python如何创建一个实例对象
时间: 2023-09-12 20:07:52 浏览: 87
在Python中,我们可以通过以下语法创建一个实例对象:
```python
class ClassName:
def __init__(self, arg1, arg2, ...):
# 初始化操作
...
# 创建实例对象
obj = ClassName(arg1_val, arg2_val, ...)
```
在这个语法中,`ClassName`是类的名称,`__init__`是构造函数的名称,`self`是一个特殊的参数,表示类的实例对象,后面的`arg1`、`arg2`等是构造函数的参数列表。我们可以通过调用`ClassName`的构造函数来创建一个实例对象。
例如,如果我们有一个名为`Person`的类,它有一个构造函数`__init__`,接受两个参数`name`和`age`,我们可以通过以下代码创建一个名为`person`的`Person`对象:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 创建实例对象
person = Person("Tom", 20)
```
在这个示例中,我们创建了一个名为`person`的`Person`对象,将`name`设为`Tom`,`age`设为`20`。
阅读全文
相关推荐
















