Python 实例方法语法

问题描述 投票:0回答:1

所以,我有一个 Data 类,其中许多变量被初始化为列表。 我想创建一个具有如下语法的方法:

class Data:
    def __init__(self):
        self.motors = [B, C, A, W, Z, X, T]
        self.valves = [B, C, A, W, Z, X, T]
        self.process_signals = [B, C, A, W, Z, X, T]
        self.general_signals = [B, C, A, W, Z, X, T]
        self.external_modules = [B, C, A, W, Z, X, T]
        self.automatics = [B, C, A, W, Z, X, T]
    def sort_by_name(self):
        #here some code that would return an alphabetically sorted list, but there i have no problem

and then later I would write something like this:

Data = Data()
some_list = Data.motors.sort_by_name()
some_other_list = Data.valves.sort_by_name()

and the two lists above would be sorted.

I'm new to classes and I'm not sure how to achieve this.
python class methods instance
1个回答
0
投票

在这种情况下你可以这样做

Data.motors.sort()

因为 sort() 方法已经由 python 在列表类上为您实现,并且完全符合您的要求。

为了完全满足您的要求,您必须创建另一个类并将其嵌入到您的数据类中。

所以你会有一个数据类,并且在其中你会有

self.motors = Motor()

然后在 Motor 类中,您将拥有按名称排序的方法。然而就像我上面说的,由于你的电机和阀门属性现在只是列表,你可以使用Python提供的内置方法

这是使用 python 提供的 .sort() 的代码。

class Data:
    def __init__(self):
        self.motors = [B, C, A, W, Z, X, T]
        self.valves = [B, C, A, W, Z, X, T]
        self.process_signals = [B, C, A, W, Z, X, T]
        self.general_signals = [B, C, A, W, Z, X, T]
        self.external_modules = [B, C, A, W, Z, X, T]
        self.automatics = [B, C, A, W, Z, X, T]

data = Data() # make sure not to name your variable the same thing as your class name
some_list = data.motors.sort()
some_other_list = data.valves.sort()
© www.soinside.com 2019 - 2024. All rights reserved.