设置正确类型的类属性

2024-06-13 03:49:00 发布

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

什么样的信息应该被设置为我的类的属性,这是最有意思的说法?你知道吗

例如,我有一个名为Human的类,该类的属性接受变量中的特定数据。你知道吗

  • 头发必须是黑色、金色或粗壮
  • 年龄不能超过110岁
  • 腿和手必须是整数。你知道吗
  • 名称必须是字符串等

实现这一目标的最佳方法是什么?你知道吗

class Human:
    def __init__(self,name,legs,hands,age):
        self.name = name #must be a string
        self.legs = legs #must not be more than 2
        self.hands = hands #same goes as legs above
        self.age = age #must not be above 110
        self.hair = hair #must be among hair_list =  ['black','blonde','bold']

Tags: 数据nameself信息age属性notbe
2条回答

处理托管属性的一种方法是使用descriptors。示例:

class Name(object):
    def __get__(self, instance, owner):
        return self._name

    def __set__(self, instance, name):
        if not isinstance(name, basestring):
            raise ValueError('Name must be a string')
        self._name = name


class Human(object):
    name = Name()

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

演示:

>>> h = Human(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 15, in __init__
    self.name = name
  File "test.py", line 7, in __set__
    raise ValueError('Name must be a string')
ValueError: Name must be a string
>>> h = Human('test')
>>> h.name
'test'

另请参见:Introduction to Python descriptors。你知道吗

我认为没有比明确表达你的意图更好的方法了,尽管也许你可以相信任何创建Human对象的人都会明白你不可能是500岁。你知道吗

我认为最具python风格的方法是在其中一个属性未验证时raise一个有意义的异常。我还将使用默认参数,这样您就不必再次键入最常见的用例。。你知道吗

class Human:
    def __init__(self, name, legs=2, hands=2, age=0, hair='blonde'):
        if not isinstance(name, str):
            raise TypeError("Name must be a string")
        self.name = name 

        if legs > 2:
            raise ValueError("More than 2 legs")
        self.legs = legs 

        if hands > 2:
            raise ValueError("More than 2 hands")
        self.hands = hands 

        if age > 110:
            raise ValueError("What, are you immortal?!")
        self.age = age 

        if hair not in ['black', 'blonde', 'bold']:
            raise ValueError("I'm sorry your hair color is not cool enough")
        self.hair = hair 

示例:

In [15]: Human(123)
                                     -
TypeError                                 Traceback (most recent call last)
<ipython-input-15-9998e6013647> in <module>()
  > 1 Human(123)

<ipython-input-13-65da6758e98d> in __init__(self, name, legs, hands, age, hair)
      2     def __init__(self, name, legs=2, hands=2, age=0, hair='blonde'):
      3         if not isinstance(name, str):
  > 4             raise TypeError("Name must be a string")
      5         self.name = name
      6 

TypeError: Name must be a string

另一个。。你知道吗

In [16]: Human("John", age=1500)
                                     -
ValueError                                Traceback (most recent call last)
<ipython-input-16-09f5670add7c> in <module>()
  > 1 Human("John", age=1500)

<ipython-input-13-65da6758e98d> in __init__(self, name, legs, hands, age, hair)
     17 
     18         if age > 110:
 -> 19             raise ValueError("What, are you immortal?!")
     20         self.age = age
     21 

ValueError: What, are you immortal?!

相关问题 更多 >