返回 Python 类中的所有类变量值

Var*_*rma 5 python class class-method

我有一个包含所有 AWS 区域的 Python 类。我编写了一个类方法,它将返回所有区域的列表。有没有更好的方法来返回所有类变量值,这样我就不必像下面的示例中那样对 return 语句中的所有值进行硬编码?

class AwsRegion():
    '''
    Class to define AWS Regions
    '''
    OHIO = 'us-east-2'
    NORTH_VIRGINIA = 'us-east-1'
    NORTH_CALIFORNIA = 'us-west-1'
    OREGON = 'us-west-2'
    MUMBAI = 'ap-south-1'
    SEOUL = 'ap-northeast-2'
    SINGAPORE = 'ap-southeast-1'
    SYDNEY = 'ap-southeast-2'
    TOKYO = 'ap-northeast-1'
    FRANKFURT = 'eu-central-1'
    IRELAND = 'eu-west-1'
    LONDON = 'eu-west-2'
    SAO_PAULO = 'sa-east-1'

    @classmethod
    def all(cls, ):
        return [AwsRegion.OHIO, AwsRegion.NORTH_VIRGINIA, AwsRegion.NORTH_CALIFORNIA, AwsRegion.OREGON, \
            AwsRegion.MUMBAI, AwsRegion.SEOUL, AwsRegion.SINGAPORE, AwsRegion.SYDNEY, AwsRegion.TOKYO, \
            AwsRegion.FRANKFURT, AwsRegion.IRELAND, AwsRegion.LONDON, AwsRegion.SAO_PAULO]
Run Code Online (Sandbox Code Playgroud)

sty*_*ybl 6

作为一般参考,您可以通过以下方式获取任何类的属性。
根据您的需求选择:

__dict__:

将返回所有可写类属性的字典。这通常就是您所需要的。

my_obj = MyClass()
attributes = my_obj.__dict__
Run Code Online (Sandbox Code Playgroud)

vars():

结果与 相同__dict__,但使用它被认为是最佳实践。

my_obj = MyClass()
attributes = vars(my_obj)
Run Code Online (Sandbox Code Playgroud)

dir():

将返回所有类属性,包括那些不是由您创建但继承自object.

my_obj = MyClass()
attributes = dir(my_obj)
Run Code Online (Sandbox Code Playgroud)

在您的情况下,使用vars()效果很好,正如 Martijn Pieters 在他的回答中所证明的那样。


Mar*_*ers 5

在这种情况下,您可以枚举该类的所有大写属性;我将使用该vars()函数来访问类名称空间:

@classmethod
def all(cls):
    return [value for name, value in vars(cls).items() if name.isupper()]
Run Code Online (Sandbox Code Playgroud)

演示:

>>> class AwsRegion():
...     '''
...     Class to define AWS Regions
...     '''
...     OHIO = 'us-east-2'
...     NORTH_VIRGINIA = 'us-east-1'
...     NORTH_CALIFORNIA = 'us-west-1'
...     OREGON = 'us-west-2'
...     MUMBAI = 'ap-south-1'
...     SEOUL = 'ap-northeast-2'
...     SINGAPORE = 'ap-southeast-1'
...     SYDNEY = 'ap-southeast-2'
...     TOKYO = 'ap-northeast-1'
...     FRANKFURT = 'eu-central-1'
...     IRELAND = 'eu-west-1'
...     LONDON = 'eu-west-2'
...     SAO_PAULO = 'sa-east-1'
...     @classmethod
...     def all(cls):
...         return [value for name, value in vars(cls).items() if name.isupper()]
...
>>> AwsRegion.all()
['us-east-2', 'us-east-1', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'sa-east-1']
Run Code Online (Sandbox Code Playgroud)