Python初学者必知:如何创建和使用类?
在Python中,类是一种模板或蓝图,它定义了对象的属性(数据)以及方法(行为)。以下是创建和使用类的基本步骤:
定义一个类:
class MyClass:
# 类的初始化语句,通常定义一些默认值
def __init__(self, name):
self.name = name
# 定义类的方法
def say_hello(self):
return f"Hello, {self.name}!"
- 创建对象:
```python
obj1 = MyClass(“Alice”)
obj2 = MyClass(“Bob”)
print(obj1.say_hello()) # 输出:Hello, Alice!
print(obj2.say_hello()) # 输出:Hello, Bob!
3. **类的继承**:
如果你需要创建一个具有父类属性和方法的新类,可以使用`class B(A):`来定义子类。例如:
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
def speak(self):
return "Woof!"
cat = Cat("Fluffy")
print(cat.speak()) # 输出:Meow!
现在你了解了如何在Python中创建和使用类。
还没有评论,来说两句吧...