如何通过一个类中的多个方法传递一个参数

2024-10-03 11:16:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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)之前。你知道吗

我在这里找到了一些类似的答案,但我需要一个更简单的解释。你知道吗


Tags: 方法self参数return属性exampledef错误
2条回答
class Example:
  def __init__(self, x):
    self.x = x

  def square(self):
    return self.x**2

  def cube(self):
    return self.x**3

  def squarethencube(self):
    return (self.x**2)**3
two = Example(2)

print(two.squarethencube())

当前,squarecube是绑定到类的方法;但是,您可以通过类名在squarethencube中访问它们,但它们是方法,因此依赖于实例对类的引用。因此,您可以创建该类的两个新实例或使用classmethod

选项1:

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(self, y):
      sq = Example(y).square()
      cu = Example(y).cube()
      return cu

选项2:使用classmethod:

class Example(object):

   def __init__(self, x):
      self.x = x
   @classmethod
   def square(cls, x):
      return x**2
   @classmethod
   def cube(cls, x):
      return x**3

   def squarethencube(self, y):
      sq = Example.square(y)
      cu = Example.cube(sq)
      return cu

相关问题 更多 >