杰瑞科技汇

Python中object与class的关系是什么?

Of course! Let's break down Python's object and class system in a clear, structured way. This is the foundation of Object-Oriented Programming (OOP) in Python.

Python中object与class的关系是什么?-图1
(图片来源网络,侵删)

The Big Picture: What is a Class?

Think of a class as a blueprint or a template. It defines a set of attributes (data) and methods (functions) that a certain type of object will have.

For example, the blueprint for a Car might define that every car has:

  • Attributes (Data): color, model, speed, is_engine_on
  • Methods (Functions): start_engine(), accelerate(), brake(), stop_engine()

This blueprint itself is not a car; it's just the plan. You can't "drive" a blueprint.

The Instance: What is an Object?

An object is an instance of a class. It's a concrete item created from the blueprint. It has actual values for its attributes.

Python中object与class的关系是什么?-图2
(图片来源网络,侵删)

Using our Car blueprint, we can create specific objects:

  • my_tesla = Car() might be a red Model 3 with a speed of 0.
  • your_ford = Car() might be a blue F-150 with a speed of 0.

Now my_tesla and your_ford are real, usable objects. You can call their methods: my_tesla.start_engine().


Creating a Class and an Object

Let's build the Car class in Python.

The __init__ Method: The Constructor

When you create an object from a class, a special method called __init__ (short for "initialize") is automatically called. This is where you set up the object's initial attributes.

Python中object与class的关系是什么?-图3
(图片来源网络,侵删)
  • self: This is a special parameter that refers to the specific instance of the class being created. Python passes it automatically. You use self to access the object's attributes and methods from within the class.

Example Code:

# 1. Define the Class (the blueprint)
class Car:
    # This is the constructor method. It runs when a new Car object is created.
    def __init__(self, color, model):
        # 'self' refers to the specific car instance being created.
        # We create attributes and assign them the values passed in.
        self.color = color
        self.model = model
        self.speed = 0  # All cars start with a speed of 0
        self.is_engine_on = False # The engine is off by default
    # This is a method (a function inside a class)
    def start_engine(self):
        if not self.is_engine_on:
            self.is_engine_on = True
            print(f"The {self.color} {self.model}'s engine is now on.")
        else:
            print(f"The {self.color} {self.model}'s engine is already on.")
    # Another method
    def accelerate(self, amount):
        if self.is_engine_on:
            self.speed += amount
            print(f"Accelerating. Current speed: {self.speed} km/h.")
        else:
            print("Cannot accelerate. The engine is off!")
    # A method to display the car's status
    def display_status(self):
        print(f"--- Car Status ---")
        print(f"Model: {self.model}")
        print(f"Color: {self.color}")
        print(f"Speed: {self.speed} km/h")
        print(f"Engine: {'On' if self.is_engine_on else 'Off'}")
        print("------------------")
# 2. Create Objects (instances from the blueprint)
# We call the class name like a function, which triggers the __init__ method.
my_tesla = Car(color="Red", model="Model 3")
your_ford = Car(color="Blue", model="F-150")
# 3. Use the Objects
# Access attributes using dot notation
print(f"My car is a {my_tesla.color} {my_tesla.model}.")
# Output: My car is a Red Model 3.
# Call methods using dot notation
print("\n--- Interacting with my_tesla ---")
my_tesla.accelerate(50) # This will do nothing because the engine is off.
my_tesla.start_engine() # Start the engine
my_tesla.accelerate(50) # Now it can accelerate
my_tesla.accelerate(30)
my_tesla.display_status()
print("\n--- Interacting with your_ford ---")
your_ford.start_engine()
your_ford.accelerate(20)
your_ford.display_status()

Core Concepts in Python Classes

a) The self Parameter

self is the most important concept to grasp. It's a reference to the current object instance. When you write self.speed = 0, you are saying, "Set the speed attribute for this specific object to 0."

Without self, Python wouldn't know if speed is a local variable or an attribute of the object.

b) Instance Attributes vs. Class Attributes

  • Instance Attributes: Data that is unique to each object. They are defined inside the __init__ method (e.g., self.color, self.speed).
  • Class Attributes: Data that is shared by all instances of a class. They are defined directly inside the class, but outside of any methods.

Example:

class Dog:
    # This is a CLASS attribute. All dogs will share this.
    species = "Canis familiaris"
    def __init__(self, name, age):
        # These are INSTANCE attributes. Each dog has its own name and age.
        self.name = name
        self.age = age
# Create two dog objects
dog1 = Dog("Buddy", 5)
dog2 = Dog("Lucy", 3)
# Accessing attributes
print(f"{dog1.name} is a {dog1.species}.") # Output: Buddy is a Canis familiaris.
print(f"{dog2.name} is a {dog2.species}.") # Output: Lucy is a Canis familiaris.
# Change a class attribute
Dog.species = "Canis lupus" # This affects all instances
print(f"{dog1.name} is now a {dog1.species}.") # Output: Buddy is now a Canis lupus.

c) The __str__ and __repr__ Methods

These are "dunder" (double underscore) methods that define how your object should be represented as a string.

  • __str__: A user-friendly, readable string representation. Called by print() and str().
  • __repr__: An unambiguous, developer-focused string representation. Its goal is to be so complete that you could, ideally, recreate the object from it. Called by the repr() function and in interactive shells.

Example:

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
    def __str__(self):
        # This is what the user sees
        return f"'{self.title}' by {self.author}"
    def __repr__(self):
        # This is what the developer sees. Should be unambiguous.
        return f"Book(title='{self.title}', author='{self.author}')"
my_book = Book("The Hobbit", "J.R.R. Tolkien")
print(my_book)  # Calls __str__
# Output: 'The Hobbit' by J.R.R. Tolkien
print(repr(my_book)) # Calls __repr__
# Output: Book(title='The Hobbit', author='J.R.R. Tolkien')

The object Class: The Ultimate Parent

In Python, every class inherits from a base class called object. Even when you don't specify it, it's there.

class MyClass:
    pass
# This is the same as:
class MyClass(object):
    pass

This is why all Python objects have certain "magic" methods like __str__, __repr__, __init__, etc. They are inherited from the object class. This inheritance is the basis of Object-Oriented Programming, allowing for concepts like Polymorphism and Encapsulation.

分享:
扫描分享到社交APP
上一篇
下一篇