[100 days proficient in python] Day12: Basic syntax and examples of object-oriented programming_attributes and inheritance

      Table of contents

1 Attributes

1.1 Basic syntax of attributes

1.2 Create properties for calculation

1.3 Security Protection Mechanism of Attributes

2 Inheritance

2.1 The basic syntax of inheritance

2.2 Method rewriting

2.3 Call the _init_() method of the base class in the derived class

3 summary 


         Properties are characteristics or data members of a class and can contain various data types such as integers, strings, lists, etc. Attributes allow us to define various characteristics and behaviors for a class.

        Inheritance is a relationship between classes that allows one class (called a subclass) to inherit the properties and methods of another class (called a parent class). Through inheritance, subclasses can reuse the functions of the parent class, and can also add new properties and methods as needed.

  • Properties represent the state or data of an object and are characteristics of an object. In object-oriented programming, classes can define properties, and instances have concrete values ​​for those properties.
  • Inheritance is a relationship between objects. One class can inherit the properties and methods of another class, thereby reusing existing code and extending functions.
  • Inheritance allows us to establish a class hierarchy and inherit specific subclasses from abstract classes. Subclasses can have all the properties and methods of the parent class, and can also add their own unique properties and methods as needed.

1 Attributes

In Python, attributes can be created by defining variables in a class. These variables are called instance variables or properties. Every instance variable belongs to an instance of the class and can be assigned different values ​​as needed.

1.1 Basic syntax of attributes

Defining attributes: Attributes are usually defined inside a class, and attributes can be created by declaring variables in the class. Attributes can be instance attributes (belonging to an instance of a class) or class attributes (belonging to the class itself).

class MyClass:
    # 定义实例属性
    instance_var = 10
    
    def __init__(self):
        # 初始化实例属性
        self.name = "John"

Accessing attributes:self Instance attributescan be accessed by using keywords in the methods of the classFor class properties, you can use the class name to access.

class MyClass:
    class_var = 20
    
    def __init__(self):
        self.instance_var = 10
        
    def get_class_var(self):
        # 访问类属性
        return MyClass.class_var
    
    def get_instance_var(self):
        # 访问实例属性
        return self.instance_var

Modifying attributes: Class methods canselfmodify the value of instance attributes through keywords.

class MyClass:
    def __init__(self):
        self.instance_var = 10
        
    def set_instance_var(self, value):
        # 修改实例属性的值
        self.instance_var = value

Visibility of attributes: In Python, by default, all attributes of a class are public and can be accessed outside the class. If you want to make a property private, you can add two underscores before the property name__.

class MyClass:
    def __init__(self):
        # 私有属性
        self.__private_var = 10
        
    def get_private_var(self):
        # 访问私有属性
        return self.__private_var
    
    def set_private_var(self, value):
        # 修改私有属性的值
        self.__private_var = value

Decorators for properties: A decorator can be used@propertyto convert a method of a class into a property. This allows methods to be called as if they were accessed when using the property.

class MyClass:
    def __init__(self):
        self.__private_var = 10
        
    @property
    def private_var(self):
        # 使用装饰器将方法转换为属性
        return self.__private_var

Example:

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

car1 = Car("Toyota", "Corolla", 2022)
car2 = Car("Honda", "Civic", 2021)

print(car1.make)  # 输出:Toyota
print(car2.year)  # 输出:2021

In the above example, we created a class called Car and __init__defined three properties in the initialization method: make, model, and year. We then created two instances of the Car class and assigned different values ​​to each instance.

1.2 Create properties for calculation

        In Python, we can use the @property decorator to create properties for computation. A computed property is a property whose value is calculated by calling a specific method, rather than stored directly in an instance variable. Computed properties can be calculated from the values ​​of other instance variables, or perform complex calculation logic.

        The syntax format for computed properties can be created using the @property decorator. The @property decorator allows us to turn a method into a read-only property whose value is computed rather than stored in an instance variable.

        The following is the syntax format of @property:

class ClassName:
    def __init__(self, ...):
        # 初始化实例变量

    @property
    def attribute_name(self):
        # 计算属性的逻辑
        return computed_value

In the syntax format above:

  • ClassNameis the name of the class, indicating that we are defining a class.
  • ...Is __init__the method's parameter list, used to initialize instance variables.
  • attribute_nameIt is the name of the calculated property, which can be specified according to the actual situation.
  • computed_valueIt is an attribute value obtained through calculation and can be calculated according to the actual situation.

A method can be defined as a computed property using the @property decorator, and it can be accessed like a normal property. When accessing a computed property, the method decorated with @property is actually called, and the return value of the method is returned as the property value.

When using the @property decorator, you need to pay attention to the following points:

  1. The names of computed properties and instance variables should be different, otherwise infinite recursion will result.
  2. Computed properties can only be read, not modified. If you want to modify the value of a computed property, you need to define a corresponding setter method and use the @property.setter decorator.

Here is an example showing how to create a computed property:

class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def diameter(self):
        return self.radius * 2

    @property
    def area(self):
        return 3.14 * (self.radius ** 2)

    @property
    def circumference(self):
        return 2 * 3.14 * self.radius

# 创建Circle对象
circle = Circle(5)

# 访问计算属性
print(circle.diameter)  # 输出:10
print(circle.area)  # 输出:78.5
print(circle.circumference)  # 输出:31.400000000000002

# 修改radius属性并重新计算计算属性
circle.radius = 8
print(circle.diameter)  # 输出:16
print(circle.area)  # 输出:201.12
print(circle.circumference)  # 输出:50.24

        In the above example, we created a class called Circle that contains a radius property and three computed properties: diameter, area, and circumference. Through the @property decorator, we define these three methods as computed properties, and obtain the calculated results by accessing these computed properties.

        Computed properties can dynamically calculate property values ​​without requiring additional storage space, thus saving memory and code maintenance costs. In practical applications, computed properties are often used to calculate related values ​​based on other properties of the object, or to perform complex mathematical calculations and logical operations.

1.3 Security Protection Mechanism of Attributes

In Python, you can set security mechanisms for attributes by setting access controls to prevent accidental modification or access to attributes. In Python, there are two commonly used access control methods: public access and private access.

Public access: Public access is Python's default attribute access method, that is, all attributes can be directly accessed and modified. There is no access control in this way, and the access and modification of attributes are completely open. For example:

class Circle:
    def __init__(self, radius):
        self.radius = radius

circle = Circle(5)
print(circle.radius)  # 输出:5
circle.radius = 8
print(circle.radius)  # 输出:8

Private access: In order to set up a security mechanism, you can add two underscores "__" before the property name to set the property as a private property. Private properties can only be accessed inside the class, and cannot be directly accessed and modified externally. To access private properties, indirect access is possible through public access interfaces. For example:

class Circle:
    def __init__(self, radius):
        self.__radius = radius

    def get_radius(self):
        return self.__radius

    def set_radius(self, radius):
        if radius > 0:
            self.__radius = radius

circle = Circle(5)
print(circle.get_radius())  # 输出:5
# 试图直接访问私有属性将报错
# print(circle.__radius)  # 报错:'Circle' object has no attribute '__radius'

circle.set_radius(8)
print(circle.get_radius())  # 输出:8

Through the above example, we add two underscores "__" before the attribute name, and set the radius attribute as a private attribute. In order to access and modify private attributes, we define public access interfaces get_radius() and set_radius(), through which private attributes can be accessed and modified indirectly.

By using private attributes and public access interfaces, the access and modification of attributes can be controlled within the class, thereby achieving attribute security. In this way, the property can be prevented from being improperly modified by the outside, and the integrity and data security of the property can be protected.

2 Inheritance

        Inheritance is an important concept in object-oriented programming, which allows us to create a new class (called a subclass) that inherits the properties and methods of another existing class (called a parent class). Subclasses can inherit all public members of the parent class, and can also add their own members. Inheritance makes code reuse and organization easier and more efficient.

2.1 The basic syntax of inheritance

class ParentClass:
    # 父类的属性和方法

class ChildClass(ParentClass):
    # 子类继承父类的属性和方法,并可以添加自己的属性和方法

In the above syntax, we first define a parent class ParentClass, which contains some properties and methods. Then we define a subclass ChildClass, and specify the parent class name ParentClass in parentheses. The subclass ChildClass inherits all the properties and methods of the parent class ParentClass, and can also add its own properties and methods.

        In Python, inheritance can be achieved by passing the parent class as an argument to the child class. The subclass will inherit the properties and methods of the parent class, and can add new properties and methods when needed.

        The following is a simple example that demonstrates how to create a parent class and a child class, and obtain the properties and methods of the parent class through inheritance:

# 定义父类
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def make_sound(self):
        pass

# 定义子类,并继承父类Animal
class Dog(Animal):
    def __init__(self, name, breed):
        # 调用父类的构造函数
        super().__init__(name, species="Dog")
        self.breed = breed

    def make_sound(self):
        return "Woof!"

# 创建子类对象
dog = Dog("Buddy", "Labrador")
print(dog.name)  # 输出:Buddy
print(dog.species)  # 输出:Dog
print(dog.breed)  # 输出:Labrador
print(dog.make_sound())  # 输出:Woof!

In the above example, we defined an Animal parent class, which contains two attributes name and species, and an abstract method make_sound. Then we defined a Dog subclass, and obtained the properties and methods of the parent class Animal through inheritance. In the subclass, we also added an own property breed and implemented the make_sound method. Through inheritance, we can reuse the code of the parent class in the subclass, and can also extend and customize the functions of the subclass. 

2.2 Method rewriting

        Method Overriding (Method Overriding) is an important concept in object-oriented programming, which allows subclasses to override (rewrite) existing methods in the parent class, thereby realizing the customization and extension of methods. When a method with the same name as the parent class is defined in the subclass, the method of the subclass will override the method of the parent class, so that when the method is called in the subclass object, the implementation in the subclass will be executed instead of the implementation of the parent class.

        The basic syntax for overriding methods is as follows:

class ParentClass:
    def some_method(self):
        # 父类的方法实现

class ChildClass(ParentClass):
    def some_method(self):
        # 子类重写的方法实现

In the above syntax, we have defined a parent class ParentClass which contains a method called some_method. Then we define a subclass ChildClass and redefine the some_method method in it. When the subclass object calls the some_method method, the method implementation of the subclass will be executed.

Here's an example that demonstrates how to override a method of a parent class in a subclass:

# 定义父类
class Animal:
    def make_sound(self):
        return "Some generic sound"

# 定义子类,并继承父类Animal
class Dog(Animal):
    def make_sound(self):
        return "Woof!"

# 创建子类对象
dog = Dog()
print(dog.make_sound())  # 输出:Woof!

In the above example, we defined a parent class Animal that contains a make_sound method that returns a generic sound string. Then we define a Dog subclass and override the make_sound method in it to return "Woof!". When we create a subclass object and call the make_sound method, the method rewritten in the subclass Dog will be executed, and "Woof!" will be output instead of the implementation in the parent class Animal. This is the role of method overriding, which allows subclasses to customize and extend the methods of the parent class when needed. 

2.3 Call the _init_() method of the base class in the derived class

Calling a method of a base class (parent class) in a derived class (subclass) __init__()can be achieved by using super()a function. super()Functions are Python built-in functions that are used to access methods and properties of parent classes.

__init__()Using super()the function in the method of the derived class , you can call the constructor of the parent class in the constructor of the subclass first, and then add the initialization code of the subclass itself. This ensures that subclass objects are initialized with properties from the superclass.

Here is an example that demonstrates how to call __init__()a method of a base class in a subclass:

class ParentClass:
    def __init__(self, name):
        self.name = name

class ChildClass(ParentClass):
    def __init__(self, name, age):
        super().__init__(name)  # 调用父类的__init__方法
        self.age = age

# 创建子类对象
child = ChildClass("Alice", 25)
print(child.name)  # 输出:Alice
print(child.age)   # 输出:25

In the above example, we defined a parent class ParentClasswith a __init__()method for initializing nameproperties.

Another subclass is defined ChildClass, and the method of calling the parent class __init__()is used in its method , so that the attribute is set when the subclass object is initialized .super().__init__(name)__init__()name

Then we added the subclass's own initialization code, setting ageproperties. Finally, we created the subclass object and accessed namethe and ageattributes, verifying __init__()the correctness of calling the base class method.

3 summary 

Attributes:

  • A property is used to store data or calculate property values, and is one of the members of a class.
  • Properties can be defined in a class by declaring variables in the class body. Attributes can be instance attributes (belonging to an instance of a class) or class attributes (belonging to the class itself).
  • Instance attributes selfare accessed and modified in the methods of the class through keywords, while class attributes can be accessed using the class name.
  • A decorator can be used @propertyto convert a method into a property, enabling computation and access control of properties.
  • Properties can be made private by prefixing the property name with two underscores __.

inherit:

  • Inheritance is a mechanism for realizing code reuse in object-oriented programming, which allows a class (derived class) to inherit the properties and methods of another class (base class).
  • The derived class can get all the properties and methods of the base class, and can add new properties and methods in the derived class, or override the methods of the base class.
  • The inheritance relationship forms a class hierarchy, and subclasses inherit the characteristics of the parent class, and can further derive more subclasses.
  • Using inheritance can reduce code duplication and improve code maintainability and scalability.

Guess you like

Origin blog.csdn.net/qq_35831906/article/details/131877627
Recommended