Question

I am learning about classes and member functions, and I would like to know what is the correct way to implement this:

class window:

  def __init__(self,x,y,width,height):
    self.x=x
    self.y=y
    self.width=width
    self.height=height

  def shift(self,shift_x,shift_y):
    self.x=self.x+shift_x
    self.y=self.y+shift_y

  def divide(self):
    window A
    A.x=(self.x)/2
    A.y=(self.y)/2
    A.width=(self.width)/2
    A.height=(self.height)/2
    return A

How do I implement the divide function correctly? where I want it to return the same class? I know I am predefining A like in C++, but I'm not sure if this is necessary or what is the correct workaround, since I'm getting an error for doing that

Était-ce utile?

La solution

It looks like what you want is:

def divide(self):
    newWindow = window(self.x/2, self.y/2, self.width/2, self.height/2)
    return newWindow

To create an instance of a class, you call it, like window(...), passing whatever arguments it needs.

You should read the Python tutorial to familiarze yourself with the basics of Python.

Autres conseils

A = window(self.x/2, self.y/2, self.width/2, self.height/2)

Exactly the same way you'd create an object outside the class.

Instantiating a class is done with my_instance = MyClass(). You should probably take a look at the official Python tutorial's section on classes and objects: http://docs.python.org/2/tutorial/classes.html

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top