Python 从另一个类调用方法

Python 从另一个类调用方法,python,list,class,Python,List,Class,到目前为止,我遇到的问题是,当我从另一个类调用函数时,它会抛出一个错误 开关类的作用是: 如果您将“1”作为参数传递,它将把它更改为True;如果您将“0”作为参数传递,它将把它更改为False。Switch中的flip方法会更改模式,因此如果为真,则会将其更改为假,以此类推 Flip类的作用是: 如果您传递一个数字作为参数,它将创建一个包含那么多元素的列表,但它会将False放在适当的位置,而不是数字。如果你通过10,而不是[0,1,2,3,4,5,6,7,8,9],你会得到[False,Fa

到目前为止,我遇到的问题是,当我从另一个类调用函数时,它会抛出一个错误

开关类的作用是:

如果您将“1”作为参数传递,它将把它更改为True;如果您将“0”作为参数传递,它将把它更改为False。Switch中的flip方法会更改模式,因此如果为真,则会将其更改为假,以此类推

Flip类的作用是:

如果您传递一个数字作为参数,它将创建一个包含那么多元素的列表,但它会将False放在适当的位置,而不是数字。如果你通过10,而不是[0,1,2,3,4,5,6,7,8,9],你会得到[False,False,False,…]。flip中的flip方法将从Switch调用flip方法,并在给定索引处更改其状态。你用2作为n调用flip,然后你会得到[False,False,True]

但是,当I.flip(2)时,它会抛出一个错误:

class Switch():

    def __init__(self, mode):
        self._mode = mode
        if self._mode == '1':
            self._mode = True
        if self._mode == '0':
            self._mode = False

    def flip(self):
        if self._mode is True:
            self._mode = False
        if self._mode is False:
            self._mode = True


class Flip():

    def __init__(self, lst):
        self._lst = []
        for i in range(lst):
            self._lst.append(False)

    def flip(self, n):
        self._lst[n] = Switch.flip(self) #problem here
f1=Flip(10)
f1.翻转(2)
回溯(最近一次呼叫最后一次):
文件“C:\Program Files(x86)\Wing IDE 101 4.1\src\debug\tserver\\u sandbox.py”,第1行,在
#在内部用于外部解释器下的调试沙盒
文件“C:\Program Files(x86)\Wing IDE 101 4.1\src\debug\tserver\\u sandbox.py”,第25行,在flip中
文件“C:\Program Files(x86)\Wing IDE 101 4.1\src\debug\tserver\\u sandbox.py”,第11行,在flip中
builtins.AttributeError:“Flip”对象没有属性“\u mode”

不确定要更改什么才能解决此问题。类对我来说是新的,所以不太确定:/

您需要创建一个带有传入的
模式
变量的
开关
对象,并删除传递给以下对象的
self
变量:

f1 = Flip(10)
f1.flip(2)
Traceback (most recent call last):
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 1, in <module>
    # Used internally for debug sandbox under external interpreter
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 25, in flip
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 11, in flip
builtins.AttributeError: 'Flip' object has no attribute '_mode'
所以它应该看起来像:

self._lst[n] = Switch.flip(self) #problem here
您有两个问题(请查看下面修改的代码,以及我的两条注释-我在其中进行了更改)


另外,所有python类都应该继承自
对象
或其后代(但这与您的问题无关)。

我认为您应该重新考虑您的类设计。这可能只是一个帮助你自学的例子。确定什么应该成为一个类的一种方法叫做“名词抽取”。首先创建一个系统如何工作的叙述(例如,“当一个人扳动开关时,一盏灯打开或关闭”),然后提取名词列表:person、switch、light。您的类将是这些名词的子集。动词(翻转、打开、关闭)成为这些类中的方法

我认为你的交换班回答了你需要的大部分问题。Flip类可能会被删除。您只需使用您拥有的代码创建一个Switch对象,并在其上运行方法:

class Switch():

    def __init__(self, mode):
        self._mode = mode
        if self._mode == '1':
            self._mode = True
        if self._mode == '0':
            self._mode = False

    def flip(self):
        if self._mode is True:
            self._mode = False
        if self._mode is False:
            self._mode = True
        return self._mode  # need to return this for Flip class's method

class Flip():

    def __init__(self, lst):
        self._lst = []
        for i in range(lst):
            self._lst.append(False)

    def flip(self, n):
        # need to initialize Switch with the current mode
        self._lst[n] = Switch(self._lst[n]).flip()  
要调用
flip()
方法,您需要有一个类
开关的实例,正如大多数答案所说的那样。通读这本书会给你一个好的开始

但是,您还有其他几个可能会混淆此代码的机会。下面是一个实现,它解决了您将来可能遇到的一些问题

myswitch = Switch(1)
print myswitch._mode
myswitch.flip()
print myswitch._mode
更改

  • 在switch类中将所有真/假值表示为布尔值
  • 布尔值可以使用
    而不是
    来反转,而不是使用条件
  • 添加了一个
    \uuuu str\uuuu
    ,它返回实例的字符串表示形式,这对调试非常有用
  • (高级)在
    Flip
    构造函数中使用循环,而不是循环。都是蟒蛇之类的索福斯
以及用法:

class Switch():

    # mode should be a boolean True/False
    def __init__(self, mode):
        self._mode = mode

    # since mode is boolean you can invert it with 'not'
    def flip(self):
        self._mode = not self._mode

    def __str__(self, ):
        return '1' if self._mode else '-'

class Flip():
    def __init__(self, switch_count ):
        # creates N Switch instances to store in the flip array
        # Switch() creates an instance
        # [ ... for x in ... ] is a list comprehension, you could just
        #    as easily leave your for loop, but this seems more like
        #    what you're trying to accomplish
        self._lst = [Switch(False) for i in range(switch_count)]

    def flip(self, n):
        # _list[n] access the Switch() instance, and flips it
        self._lst[n].flip()

    def __str__(self):
        return "Switches:" + ''.join([str(x) for x in self._lst])

我得到:builtins.TypeError:flip()缺少1个必需的位置参数:“self”您能否简化
flip
方法,使其只包含
self.\u mode=not self.\u mode
并去掉
if
语句?
class Switch():

    # mode should be a boolean True/False
    def __init__(self, mode):
        self._mode = mode

    # since mode is boolean you can invert it with 'not'
    def flip(self):
        self._mode = not self._mode

    def __str__(self, ):
        return '1' if self._mode else '-'

class Flip():
    def __init__(self, switch_count ):
        # creates N Switch instances to store in the flip array
        # Switch() creates an instance
        # [ ... for x in ... ] is a list comprehension, you could just
        #    as easily leave your for loop, but this seems more like
        #    what you're trying to accomplish
        self._lst = [Switch(False) for i in range(switch_count)]

    def flip(self, n):
        # _list[n] access the Switch() instance, and flips it
        self._lst[n].flip()

    def __str__(self):
        return "Switches:" + ''.join([str(x) for x in self._lst])
f = Flip(5)
print f
#outputs
#Switches:-----

f.flip(1)
f.flip(3)
f.flip(4)
print f
#outputs
#Switches:-1-11

f.flip(3)
f.flip(4)
print f
#outputs
#Switches:-1---