Python category

Insert image description here

Python is an object-oriented programming language, so classes are a very important concept in Python. A class is a template that defines data and behavior, allowing objects to be created and manipulated for a specific problem.

In Python, the definition of a class begins with the keyword "class", followed by the name of the class. Classes can contain methods and properties. Methods are functions in a class that define the behavior of the class, while properties are variables in the class that store data for the class.

Here is an example of a simple class:

class Person:
    # 类属性
    species = "human"

    # 类方法
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 实例方法
    def say_hello(self):
        print("Hello, my name is", self.name)

# 创建实例
person = Person("Alice", 25)

# 调用实例方法
person.say_hello()

# 访问实例属性
print(person.age)

# 访问类属性
print(Person.species)

In the above example, we have defined a class called "Person" which has a class attribute "species" and an instance method "say_hello". We also define a constructor " init " which accepts name and age parameters and stores them as instance properties. Finally, we create an instance named "person" and manipulate it by calling the say_hello method and accessing properties.

In addition, in Python, classes can also inherit the behavior of other classes. Through inheritance, subclasses can reuse properties and methods from the parent class and add their own data and behavior. Here is an inheritance example:

class Student(Person):
    # 类属性
    status = "enrolled"

    # 实例方法
    def say_status(self):
        print("I am", self.status)

# 创建子类实例
student = Student("Bob", 20)

# 调用父类方法
student.say_hello()

# 调用子类方法
student.say_status()

In the above example, we have defined a subclass called "Student" which inherits the properties and methods of the "Person" class and adds its own properties and methods. We created an instance of "student" and called the parent and child class methods.

Guess you like

Origin blog.csdn.net/Python_enjoy/article/details/132751978