在Python中,類是一種數據結構,用來封裝數據和行為。類定義了對象的屬性和方法,可以創建多個具有相同屬性和方法的對象實例。類的用法包括以下幾個方面:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is", self.name)
person1 = Person("Alice", 25)
person1.greet()
person2 = Person("Bob", 30)
person2.greet()
print(person1.name)
person1.greet()
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def study(self):
print("I am studying")
student1 = Student("Alice", 25, 12345)
student1.greet()
student1.study()
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient balance")
account1 = BankAccount(1000)
account1.deposit(500)
account1.withdraw(200)