属性与方法 #

一、实例属性 #

python
class Person:
    def __init__(self, name, age):
        self.name = name  # 实例属性
        self.age = age
    
    def introduce(self):
        return f"I'm {self.name}, {self.age} years old"

p = Person("Tom", 25)
print(p.name)  # "Tom"
p.name = "Jerry"  # 修改属性

二、类属性 #

python
class Student:
    school = "Python School"  # 类属性
    count = 0
    
    def __init__(self, name):
        self.name = name
        Student.count += 1

print(Student.school)  # "Python School"
s = Student("Tom")
print(s.count)  # 1

三、实例方法 #

python
class Counter:
    def __init__(self):
        self.count = 0
    
    def increment(self):  # 实例方法
        self.count += 1
        return self.count
    
    def reset(self):
        self.count = 0

c = Counter()
c.increment()

四、类方法 #

python
class Person:
    population = 0
    
    def __init__(self, name):
        self.name = name
        Person.population += 1
    
    @classmethod
    def get_population(cls):
        return cls.population
    
    @classmethod
    def from_string(cls, info):
        name = info.split('-')[0]
        return cls(name)

print(Person.get_population())
p = Person.from_string("Tom-25")

五、静态方法 #

python
class MathUtils:
    @staticmethod
    def add(a, b):
        return a + b
    
    @staticmethod
    def multiply(a, b):
        return a * b

print(MathUtils.add(1, 2))  # 3

六、属性装饰器 #

python
class Circle:
    def __init__(self, radius):
        self._radius = radius
    
    @property
    def radius(self):
        return self._radius
    
    @radius.setter
    def radius(self, value):
        if value >= 0:
            self._radius = value
        else:
            raise ValueError("半径不能为负")
    
    @property
    def area(self):
        return 3.14159 * self._radius ** 2

c = Circle(5)
print(c.radius)  # 5
print(c.area)    # 78.54
c.radius = 10

七、私有属性 #

python
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # 私有属性
    
    def get_balance(self):
        return self.__balance
    
    def deposit(self, amount):
        self.__balance += amount

account = BankAccount(1000)
# print(account.__balance)  # AttributeError
print(account.get_balance())  # 1000
print(account._BankAccount__balance)  # 可访问但不推荐

八、总结 #

类型 定义 访问方式
实例属性 self.name obj.name
类属性 直接定义 Class.name
实例方法 def method(self) obj.method()
类方法 @classmethod Class.method()
静态方法 @staticmethod Class.method()
属性 @property obj.prop
私有属性 __name 内部访问
最后更新:2026-03-16