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

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

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

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:

确定