简体   繁体   中英

python; how to pass one argument through multiple methods in a class

I am learning about class structure in python. Would like to know if it's possible to pass one argument through more than one method.

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())

Error is on line 10; AttributeError: 'int' object has no attribute 'x'

The goal is to use the 'squarethencube' method to pass '2' to square(), which is 4. Then pass '4' to cube(). The desired output is '64'. Obviously, you can write a function to do the math in a very simple way; the question here is how to use multiple methods.

I understand the error in that .x is getting assigned as an attribute onto the output of cube(sq). I was getting the same error, but on line 7, before I changed the argument to y (from self.x).

I've found some similar answers here but I need a simpler explanation.

Currently, square and cube are methods bound to the class; however, you are accessing them in squarethencube by class name, but they are methods, and thus rely on a reference to the class from an instance. Therefore, you can either create two new instances of the class or use classmethod :

Option1:

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

Option 2: use a 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
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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM