Python面向对象编程:创建类和对象实例
在Python中,面向对象编程(Object-Oriented Programming, OOP)是其重要特性之一。通过类来定义对象的属性和行为。
下面是如何创建类、对象以及实例化的步骤:
定义一个类:
class MyClass:
# 类的属性
attribute1 = 'default value'
# 类的方法
def method1(self):
return self.attribute1 + ' from method'
- 创建类的对象实例:
```python实例化对象
my_instance = MyClass()
访问对象的属性和方法
print(my_instance.attribute1) # 输出:default value
print(my_instance.method1()) # 输出:default value from method
```
这样,你就在Python中实现了类、对象以及实例化的操作。
还没有评论,来说两句吧...