在python3中从实例变量中获取参数

2024-09-30 08:26:37 发布

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

我正在尝试向类方法添加实例变量

目标是能够返回一个布尔值到方法-因此它会导致一个true或false

在方法(x,Y)中使用局部变量很容易,但是当我尝试使用实例变量的值时,我得到了一个错误

该代码在X和Y作为局部变量参数时运行良好

 def isNumber(x, y):
        if x < 20 or y < 2 or y > 5 :
            result = True
            print("This is great")
        else:
            result = False
            print("This is not great")
        return result

    # For test purpose, I print. 

    print(isNumber(10, 5))

但是当我尝试使用实例变量(self.baseCost=20000)时 self.machineSalesPrice=65000)它给出了一个语法错误

这是全部代码。出什么问题了

class BusinessModelType:

    def __init__(self,numberOfEmployees):


        self.baseCost = 20000
        self.machineSalesPrice = 65000

    # This Code works fine, as I'm using X and Y to test

    def isNumber(x, y):
        if x < 20 or y < 2 or y > 5 :
            result = True
            print("This is great")
        else:
            result = False
            print("This is not great")
        return result

    # For test purpose, I print. 

    print(isNumber(10, 5))


    # But when I start to use the two instance variables instead of X    and Y the code won't work 

    def isValue(self.baseCost, self.machineSalesPrice):
        if self.baseCost < 20 or self.machineSalesPrice < 2 or self.machineSalesPrice > 5 :
            result = True
            print("This is great")
        else:
            result = False
            print("This is not great")
        return result

    print(isValue())

文件“”,第60行 def isValue(self.baseCost,self.machineSalesPrice): ^ 语法错误:无效语法

目标是能够使用这些实例变量的值向方法返回布尔值


Tags: or实例方法selftrueifisdef
2条回答

我不知道你想在这里干什么。如果要从实例中获取值,它们根本不需要是参数。但是与任何实例方法一样,需要成为参数的是self对象

def isValue(self):
    if self.baseCost < 20 or self.machineSalesPrice < 2 or self.machineSalesPrice > 5 :
        result = True
        print("This is great")
    else:
        result = False
        print("This is not great")
    return result

要在类方法中使用类字段,请将self参数传递给类方法。这将允许您通过.表示法访问所有类字段

class BusinessModelType:

    def __init__(self, baseCost, machineSalesPrice):
        self.baseCost = baseCost
        self.machineSalesPrice = machineSalesPrice

    ...

    # pass `self` instead of `self.variable`
    # you can still access all variables
    def isValue(self):
        if self.baseCost < 20 or self.machineSalesPrice < 2 or self.machineSalesPrice > 5 :
            result = True
            print("This is great")
        else:
            result = False
            print("This is not great")
        return result

    ...

然后创建一个BusinessModelType对象并对其调用isValue

bmt = BusinessModelType(10, 20)
print(bmt.isValue())

相关问题 更多 >

    热门问题