设计这个类的最佳方法

2024-05-23 17:59:52 发布

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

上下文:大家好,请看这个问题。我是一名初级python程序员(两周内表现出色!)我相信我最初设计的课程很糟糕,我正在寻求帮助,寻找一个好的方法来重新设计基础课程(在Locus.py中)

背景:到目前为止,该项目有4个类,可以在这里找到(https://github.com/asriley/HalfSiblings)。非常基本的类基因座有一个元组来代表遗传数据的等位基因(a,b)。下一个类别,个体有一个等位基因列表:[(a,b),(c,d),(a,e),(f,d)]一般来说,我们有n个个体,每个个体有l个位点。

样本数据:7个个体(行),3个位点(COL)

1,1 5,3 4,3
1,2 4,7 3,7
2,3 3,6 5,4
2,4 7,4 4,9
3,6 8,9 3,0
6,5 4,8 0,0
7,7 7,7 7,9

我试图找出如何设计这个类以将它合并到其他类(尤其是单个类)中,因为最终我必须使用networkx在数据上构建图形

给出了轨迹类的完整片段和当前错误:

class Locus:
    # constructor
    def __init__(self):
        self.alleles = ()
    def get_alleles(self):
        return self._alleles    
    def set_alleles (self,x, y):
        if x and y:
            self._alleles = (x,y)
    alleles = property (get_alleles, set_alleles)

l1 = Locus()
l1.set_alleles(1,2)
l1.set_alleles(2,3)
print (l1.get_alleles()) 

Traceback (most recent call last):
  File "Locus.py", line 13, in <module>
  l1 = Locus()
  File "Locus.py", line 4, in __init__
  self.alleles = ()
TypeError: set_alleles() missing 1 required positional argument: 'y'

有谁能帮助我正确处理这门课吗

文件解析是在github链接的另一个类中完成的。所以这不是一个问题。最后,我想发送一份2D个人列表(包含基因位点信息)给其他班级


Tags: 数据pyselfgithubl1列表getdef
1条回答
网友
1楼 · 发布于 2024-05-23 17:59:52

我知道您想使用@property decorator在Locus类上获取/设置元组,这里有一种可能的方法:

class Locus:

    @property
    def alleles(self):
        return self._alleles

    @alleles.setter
    def alleles(self, value):
        try:
            x, y = value

            # ... Tuple processing goes here ...

            self._alleles = (x, y)
        except ValueError:
            raise ValueError("(x,y) tuple expected")


l1 = Locus()
l1.alleles = (1, 2)
l1.alleles = (2, 3)
print(l1.alleles)

相关问题 更多 >