英文:
Implement class method based on instance variable values (OOP)
问题
I am new to OOP. I want to create objects that have a method which depends on the instance variables value.
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
If I create the following instances c1
and c2
by the class cases
:
c1 = cases(2)
c2 = cases(5)
and execute the method x()
I expect that:
c1.x(10) # --> 10
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 discrimination?
UPDATE
By following the instructions of @deceze (2nd try). Code becomes 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.
英文:
I am new to OOP. I want to create objects that have a method which depends on the instance variables value.
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
If I create the following instances c1
and c2
by the class cases
:
c1 = cases(2)
c2 = cases(5)
and execute the method x()
I expect that:
c1.x(10) # --> 10
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 discrimination?
UPDATE
By following the instructions of @deceze (2nd try). Code becomes the followed:
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.
答案1
得分: 2
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.
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论