如何检索属性?

2024-09-27 07:29:00 发布

您现在位置:Python中文网/ 问答频道 /正文

class character():

  class personalized:
    def __init__(self, name, age, height, width, hair_color, eye_color):

      # I want to do this
      for attr in personalized:
        personalized.attr = attr


      #instead of this
      personalized.name = name
      personalized.age = age
      personalized.height = height

如果我使用的类有很多属性,我不想每次都把它设置为一个变量,因为它会占用很多空间。有没有一种方法可以像我上面写的那样,但实际上是有效的。本质上,我不知道如何从__init__函数中检索属性


Tags: nameselfage属性initdefthiswidth
3条回答

您可以使用__set__(..)函数(https://docs.python.org/3/howto/descriptor.html),但我不建议这样做,因为:

  • 从可读性的角度来看,这将很难长期维护(代码通常是读的而不是写的)
  • 每次您想要访问这样的条目时,首先必须检查描述符/属性是否可用,从而使您的后续代码变得更糟。 见: How to know if an object has an attribute in Python

使用^{}^{}可以做您想做的事情,但是如果使用Python 3.7+,我建议使用dataclasses和另一个答案一样

vars()返回局部变量字典。在__init__的顶部,字典包含self和作为键的任何参数及其值

setattr()将在对象上设置属性值

class Personalized:
    def __init__(self, name, age, height, width, hair_color, eye_color):
      for key,value in vars().items():
          if key != 'self':
              setattr(self, key, value)

p = Personalized('name',5,10,12,'black','blue')
print(p.name,p.age,p.height,p.width,p.hair_color,p.eye_color)

输出:

name 5 10 12 black blue

我建议为此使用dataclasses。在您的情况下,您只需添加:

from dataclasses import dataclass

@dataclass
class personalized:
    name: str
    age: int
    height: int
    width: int
    hair_color: str
    eye_color: str

这将使用自分配属性为您自动构造一个init

相关问题 更多 >

    热门问题