英文:
Definition of custom class and different methods
问题
我有以下定义:
def fun1(x):
return x + 2
class my_class:
def fun1(x):
return x + 22
def fun2(x):
return fun1(x) + 33
print(my_class.fun2(10))
然而,这返回的是45,而我期望的是65(10 + 22 + 33)。
我在哪里犯了错误?
英文:
I have below definition:
def fun1(x) :
return x + 2
class my_class :
def fun1(x) :
return x + 22
def fun2(x) :
return fun1(x) + 33
print(my_class.fun2(10))
However this returns 45, whereas I am expecting 65 (10 + 22 + 33).
Where am I making a mistake?
答案1
得分: 0
This can be a way out but, not a recommended style:
class my_class:
def fun1(x):
return x + 22
def fun2(x):
return my_class.fun1(x) + 33
my_class.fun2(10)
Another unorthodox way:
class my_class:
def fun1(x):
return x + 22
@classmethod
def fun2(cls, x):
return cls.fun1(x) + 33
my_class.fun2(10)
The best way I can think of:
def fun1(x):
return x + 2
class my_class:
def fun1(self, x):
return x + 22
def fun2(self, x):
return self.fun1(x) + 33 # referring to instance method self.fun1
print(my_class().fun2(10)) # my_class() is an object
英文:
This can be a way out but, not a recommended style:
class my_class:
def fun1(x) :
return x + 22
def fun2(x) :
return my_class.fun1(x) + 33
my_class.fun2(10)
Another unorthodox way:
class my_class:
def fun1(x) :
return x + 22
@classmethod
def fun2(cls,x) :
return cls.fun1(x) + 33
my_class.fun2(10)
The best way I can think of:
def fun1(x) :
return x + 2
class my_class :
def fun1(self,x) :
return x + 22
def fun2(self,x) :
return self.fun1(x) + 33 #refering to instance method self.fun1
print(my_class().fun2(10)) # my_class() is a object
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论