繁体   English   中英

Python:使用相关属性定义类

[英]Python: Defining class with dependent attributes

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

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

因此,我的问题是简化此示例:是否有更简单的方法来实现这种问题? 对于更复杂的示例,它很快变得相当复杂且难以管理。

应用

最终目标是创建一个具有所有设备属性的类,例如:

class crystal:
    absorption
    refractive_index
    transmission
    reflection
    heat_conductivity
    heat_resistance

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

对于有关编写更好的代码的任何评论,我都很客气。 即使我学习和阅读了有关面向对象编码的文献,但我对编写此类知识还是缺乏经验。

我认为使用@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

工作行为:

>>> from temp import Pythagoras
>>> p = Pythagoras(a=10, b=20)
>>> p.c
22.360679774997898

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

尝试这个:

import pandas as pd

class Pyth():
    def __init__(self, a=np.NaN, b=np.NaN, c=np.NaN):
        df = pd.DataFrame({
           'sides': [a,b,c], 
           'equation':[np.sqrt(c**2 - b**2), np.sqrt(c**2 - a**2), np.sqrt(a**2 + b**2)]
        })
        df.loc[df.sides.isnull(), 'sides'] = df[df.sides.isnull()]['equation']

        self.a = df.sides[0]
        self.b = df.sides[1]
        self.c = df.sides[2]

测试结果:

test = Pyth(a=3,b=4)
test.c
Out[217]:
5.0
In [218]:

test.b
Out[218]:
4.0
In [219]:

test.a
Out[219]:
3.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM