Python:定义具有依赖属性的类

str*_*ter 4 python class python-3.x

我的目标是编写一个可用于计算设备所有属性的类。

import numpy as np


class pythagoras:
    def __init__(self, a=None, b=None, c=None):
        self.a = a
        self.b = b
        self.c = c

        if(a == None):
            assert(b != None)
            assert(c != None)
            self.a = np.sqrt(c**2 - b**2)
        elif(b == None):
            assert(a != None)
            assert(c != None)
            self.b = np.sqrt(c**2 - a**2)
        elif(c == None):
            assert(a != None)
            assert(b != None)
            self.c = np.sqrt(a**2 + b**2)
        else:
            assert (a**2 + b**2 == c**2), "The values are incompatible."


example1 = pythagoras(a=3, b=4)
print(example.c)
# 5
example2 = pythagoras(a=3, c=5)
print(example2.b)
# 4
example3 = pythagoras(b=4, c=5)
print(example3.a)
# 3
Run Code Online (Sandbox Code Playgroud)

所以我的问题是关于简化这个例子:是否有更简单的方法来实现此类问题?对于更复杂的例子,它很快就会变得相当复杂且难以管理。

应用

最终目标是拥有一个包含所有设备属性的类,例如:

class crystal:
    absorption
    refractive_index
    transmission
    reflection
    heat_conductivity
    heat_resistance
Run Code Online (Sandbox Code Playgroud)

在这里,人们可以想象这些属性相互依赖,并且根据我对属性的了解,我可以推断出其余的属性。

对于任何关于编写更好的代码的评论,我都很感激。尽管我学习并阅读了有关面向对象编码的文献,但我在编写此类代码方面缺乏经验。

Gam*_*iac 6

我认为一旦使用装饰器,这很容易计算@property。让我给你举个例子。

导入数学

class Pythagoras(object):

    def __init__(self, a=None, b=None, c=None):
        self._a = a
        self._b = b
        self._c = c

        count = 0
        if self._a is None:
            count += 1
        if self._b is None:
            count += 1
        if self._c is None:
            count += 1

        if count > 1:
            raise Exception("More than one of the values are None.")

    @property
    def a(self):
        if self._a is None:
            return math.sqrt(self.c**2 - self.b**2)
        else:
            return self._a

    @property
    def b(self):
        if self._b is None:
            return math.sqrt(self.c**2 - self.a**2)
        else:
            return self._b

    @property
    def c(self):
        if self._c is None:
            return math.sqrt(self.a**2 + self.b**2)
        else:
            return self._c
Run Code Online (Sandbox Code Playgroud)

工作行为:

>>> from temp import Pythagoras
>>> p = Pythagoras(a=10, b=20)
>>> p.c
22.360679774997898
Run Code Online (Sandbox Code Playgroud)

编辑:更新了代码以确保其正常工作。