implement class method based on instance variable (OOP)

Question:

i am new to oop. i want to create objects that have a method which depends on the instance variables.

class cases:
    def __init__(self, a):
        self.a = a  

    def f1(self, x):
        return x

    def f2(self, x):
        return 100*x
    
    if self.a < 3:
        self.x = f1
    else:
        self.x = f2

so in the end, i expect the following:

    c1 = cases(2)
    c2 = cases(5)

with c1.x(10) = 10 and c2.x(10) = 1000

but right now the error is:

NameError: name 'self' is not defined

if i change self.a to just a in the class definition, the error is

NameError: name 'a' is not defined

so how can i access the variable instance for a case disrcimination?

UPDATE: i now followed the instructions of deceze (2nd try). code is as follows:

def f1(x):
    return x

def f2(x):
    return 100*x



class case:
    def __init__(self, a):
        self.a = a
   
    def x(self, x):
        if self.a < 3:
            return f1(x)
        else:
            return f2(x)
      
# make instances with different cases    
c1 = case(2)
c2 = case(4)

# show results
print(c1.x(10))
print(c2.x(10))

result is as desired 🙂

Asked By: zuiop

||

Answers:

You are mixing up instances and parameters.

def f1(x):
    return x

def f2(x):
    return 100*x



class case:
    def __init__(self, a):
        self.a = a
   
    def x(self, a):
        if self.a < 3:
            return f1(a)
        else:
            return f2(a)
      
# make instances with different cases    
c1 = case(2)
c2 = case(4)

# show results
print(c1.x(10))
print(c2.x(10))

Output as expected.

Answered By: quamrana
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.