[Understanding of class classes in Python]

What is class? In Python, a class is a blueprint or template for creating objects. It defines the properties and methods of the object.

1. How to define a class? Use the class keyword followed by the class name to define a class. Class names usually use camelCase notation.

class MyClass:
    pass

2. How to create an object? Create an object using the class name followed by parentheses. You can use = to assign it to a variable.

obj = MyClass()
属性和方法:

Properties are characteristics or data of a class. They are stored in objects and can be accessed through the self keyword.
Methods are behaviors or functions of a class. They are defined in classes and can be called through objects.

class Person:
    def __init__(self, name):
        self.name = name  # 属性

    def greet(self):
        return f"Hello, {
      
      self.name}!"  # 方法
person = Person("Alice")
print(person.name)  # 输出: Alice
print(person.greet())  # 输出: Hello, Alice!

3. Inheritance: Classes can inherit the properties and methods of other classes. Inheritance is achieved by passing the parent class as a parameter in the class definition.

class Student(Person):  # 继承自Person类
    def __init__(self, name, grade):
        super().__init__(name)  # 调用父类的构造函数
        self.grade = grade

    def study(self):
        return f"{
      
      self.name} is studying in grade {
      
      self.grade}."

student = Student("Bob", 5)
print(student.name)  # 输出: Bob
print(student.study())  # 输出: Bob is studying in grade 5.

Here is some basic information and sample code about classes in Python. If you want to learn more about class, here are some reference links:
Official Python Documentation Introduction to class
Python Tutorial-class
Python Object-Oriented Programming (OOP) Tutorial
Python Classes and Objects

Guess you like

Origin blog.csdn.net/der_power/article/details/132043772