我正在学习python中的类结构。想知道是否有可能通过一个以上的方法传递一个参数。你知道吗
class Example(object):
def __init__(self, x):
self.x = x
def square(self):
return self.x**2
def cube(self):
return self.x**3
def squarethencube(y):
sq = Example.square(y)
cu = Example.cube(sq)
return cu
two = Example(2)
print(two.squarethencube())
第10行有错误;AttributeError:'int'对象没有属性'x'
目标是使用'squarthencube'方法将'2'传递给square(),即4。然后将“4”传递给cube()。所需输出为“64”。显然,可以用一种非常简单的方法编写一个函数来进行计算;这里的问题是如何使用多种方法。你知道吗
我理解其中的错误,即.x被指定为cube(sq)输出的一个属性。我得到了相同的错误,但是在第7行,在我将参数改为y(从self.x)之前。你知道吗
我在这里找到了一些类似的答案,但我需要一个更简单的解释。你知道吗
当前,
square
和cube
是绑定到类的方法;但是,您可以通过类名在squarethencube
中访问它们,但它们是方法,因此依赖于实例对类的引用。因此,您可以创建该类的两个新实例或使用classmethod
:选项1:
选项2:使用classmethod:
相关问题 更多 >
编程相关推荐