自定义类的定义和不同的方法

huangapple go评论96阅读模式
英文:

Definition of custom class and different methods

问题

我有以下定义:

  1. def fun1(x):
  2. return x + 2
  3. class my_class:
  4. def fun1(x):
  5. return x + 22
  6. def fun2(x):
  7. return fun1(x) + 33
  8. print(my_class.fun2(10))

然而,这返回的是45,而我期望的是65(10 + 22 + 33)。

我在哪里犯了错误?

英文:

I have below definition:

  1. def fun1(x) :
  2. return x + 2
  3. class my_class :
  4. def fun1(x) :
  5. return x + 22
  6. def fun2(x) :
  7. return fun1(x) + 33
  8. 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:

  1. class my_class:
  2. def fun1(x):
  3. return x + 22
  4. def fun2(x):
  5. return my_class.fun1(x) + 33
  6. my_class.fun2(10)

Another unorthodox way:

  1. class my_class:
  2. def fun1(x):
  3. return x + 22
  4. @classmethod
  5. def fun2(cls, x):
  6. return cls.fun1(x) + 33
  7. my_class.fun2(10)

The best way I can think of:

  1. def fun1(x):
  2. return x + 2
  3. class my_class:
  4. def fun1(self, x):
  5. return x + 22
  6. def fun2(self, x):
  7. return self.fun1(x) + 33 # referring to instance method self.fun1
  8. print(my_class().fun2(10)) # my_class() is an object
英文:

This can be a way out but, not a recommended style:

  1. class my_class:
  2. def fun1(x) :
  3. return x + 22
  4. def fun2(x) :
  5. return my_class.fun1(x) + 33
  6. my_class.fun2(10)

Another unorthodox way:

  1. class my_class:
  2. def fun1(x) :
  3. return x + 22
  4. @classmethod
  5. def fun2(cls,x) :
  6. return cls.fun1(x) + 33
  7. my_class.fun2(10)

The best way I can think of:

  1. def fun1(x) :
  2. return x + 2
  3. class my_class :
  4. def fun1(self,x) :
  5. return x + 22
  6. def fun2(self,x) :
  7. return self.fun1(x) + 33 #refering to instance method self.fun1
  8. print(my_class().fun2(10)) # my_class() is a object

huangapple
  • 本文由 发表于 2023年4月10日 19:19:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定