Python的类学习总结

Python的类学习总结
最新回答
是态度

2026-10-22 21:44:14

Python的类是面向对象编程的核心概念,它允许你将数据和功能封装在一起。以下是对Python类的学习总结,包括类的属性、方法以及如何查看对象的属性。

1. 类的定义

在Python中,类通过class关键字定义。类可以包含属性(数据成员)和方法(函数成员)。

class MyClass: # 类属性 class_attribute = "I am a class attribute" # 初始化方法 def __init__(self, instance_attribute): self.instance_attribute = instance_attribute # 实例属性 # 实例方法 def instance_method(self): return f"Instance attribute: {self.instance_attribute}" # 类方法 @classmethod def class_method(cls): return f"Class attribute: {cls.class_attribute}" # 静态方法 @staticmethod def static_method(): return "I am a static method"2. 类的属性

类的属性包括类属性和实例属性。

  • 类属性:属于类本身,所有实例共享。
  • 实例属性:属于类的实例,每个实例可以有不同的值。
# 创建类的实例obj = MyClass("I am an instance attribute")# 访问类属性print(MyClass.class_attribute) # 输出: I am a class attribute# 访问实例属性print(obj.instance_attribute) # 输出: I am an instance attribute3. 查看对象的属性

可以使用dir()函数查看对象的所有属性和方法。dir()返回一个包含对象所有有效属性名称的列表。

# 查看对象的属性和方法print(dir(obj))

输出可能类似于:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'class_attribute', 'class_method', 'instance_attribute', 'instance_method', 'static_method']4. 特殊属性

Python对象有一些特殊属性,以双下划线__开头和结尾。这些属性通常由Python解释器使用,但也可以访问。

  • __dict__:包含对象的属性和值的字典。
  • __class__:对象所属的类。
  • __module__:定义对象的模块。
# 查看对象的__dict__属性print(obj.__dict__) # 输出: {'instance_attribute': 'I am an instance attribute'}# 查看对象的类print(obj.__class__) # 输出: <class '__main__.MyClass'>5. 动态添加属性

Python允许在运行时动态添加属性。

# 动态添加实例属性obj.new_attribute = "I am a new attribute"print(obj.new_attribute) # 输出: I am a new attribute# 动态添加类属性MyClass.new_class_attribute = "I am a new class attribute"print(MyClass.new_class_attribute) # 输出: I am a new class attributeprint(obj.new_class_attribute) # 输出: I am a new class attribute6. 删除属性

可以使用del语句删除属性。

# 删除实例属性del obj.new_attribute# print(obj.new_attribute) # 会引发AttributeError# 删除类属性del MyClass.new_class_attribute# print(MyClass.new_class_attribute) # 会引发AttributeError7. 属性访问控制

Python没有严格的私有属性,但可以通过在属性名前加单下划线_表示它是内部使用的,加双下划线__表示名称修饰(name mangling)。

class MyClassWithPrivate: def __init__(self): self._internal_attribute = "I am internal" self.__really_private = "I am really private" def get_private(self): return self.__really_privateobj_private = MyClassWithPrivate()print(obj_private._internal_attribute) # 输出: I am internal# print(obj_private.__really_private) # 会引发AttributeErrorprint(obj_private.get_private()) # 输出: I am really privateprint(obj_private._MyClassWithPrivate__really_private) # 输出: I am really private8. 属性装饰器

Python提供了@property装饰器,可以将方法转换为属性访问。

class Circle: def __init__(self, radius): self.radius = radius @property def diameter(self): return 2 * self.radius @diameter.setter def diameter(self, value): self.radius = value / 2circle = Circle(5)print(circle.diameter) # 输出: 10circle.diameter = 20print(circle.radius) # 输出: 10.09. 继承

类可以继承其他类的属性和方法。

class Parent: def __init__(self): self.parent_attribute = "I am from parent" def parent_method(self): return "Parent method"class Child(Parent): def __init__(self): super().__init__() self.child_attribute = "I am from child" def child_method(self): return "Child method"child = Child()print(child.parent_attribute) # 输出: I am from parentprint(child.child_attribute) # 输出: I am from childprint(child.parent_method()) # 输出: Parent methodprint(child.child_method()) # 输出: Child method10. 多态

多态允许不同类的对象对同一消息做出不同的响应。

class Dog: def speak(self): return "Woof!"class Cat: def speak(self): return "Meow!"def animal_speak(animal): print(animal.speak())dog = Dog()cat = Cat()animal_speak(dog) # 输出: Woof!animal_speak(cat) # 输出: Meow!总结

Python的类提供了强大的面向对象编程能力,包括属性、方法、继承、多态等特性。通过dir()函数可以方便地查看对象的属性和方法,而__dict__等特殊属性则提供了对对象内部状态的访问。动态添加和删除属性使得Python对象非常灵活。属性装饰器和名称修饰则提供了更精细的属性控制。