python 类如何设置
时间: 2023-10-13 18:07:06 浏览: 23
在 Python 中,可以使用 `class` 关键字来定义类。类的基本语法格式如下:
```
class ClassName:
# 属性
attribute = value
# 方法
def method(self, arg1, arg2, ...):
# 方法体
pass
```
其中,`ClassName` 是类的名称,可以根据需要自定义;`attribute` 是类的属性,可以为任意数据类型;`method` 是类的方法,必须至少包含一个参数 `self`,用于指向当前对象实例。
例如,下面是一个简单的 Python 类定义示例:
```python
class Person:
# 属性
name = 'Tom'
age = 18
# 方法
def say_hello(self):
print('Hello, my name is %s, and I am %d years old.' % (self.name, self.age))
```
在创建类的实例时,可以使用以下语法:
```
instance = ClassName()
```
例如,可以通过以下代码创建 `Person` 类的实例:
```python
p = Person()
```
通过实例对象调用类的属性和方法时,可以使用以下语法:
```
instance.attribute
instance.method(arg1, arg2, ...)
```
例如,可以通过以下代码访问 `Person` 类的属性和方法:
```python
print(p.name)
print(p.age)
p.say_hello()
```
输出结果如下:
```
Tom
18
Hello, my name is Tom, and I am 18 years old.
```