简体   繁体   中英

How can I access variables declared in __init__ of my class in one of it's functions

class Canvas:

  def __init__(self, size: list, void):

    self.size = size
    self.void = void

    self.canvas = []
    self.camera_pos = [0, 0]
    self.sprite_priority = []
    self.sprite = []
    self.distance_from = {}
    self.distances = []


   

    class Sprite:

      def __init__(self, char, position, z_index):

        self.char = char
        self.position = position
        self.z_index = z_index

        self.sprite.append(self)
       

      


  

  def create_canvas(void):
     
     #do code here
     #example:
     get_var = self.size #I want to get size from __init__ but self isn't recognized

So I want to get variables in any of my functions that belongs to the Canvas class but for some reason it doesn't regnonise any of those.

I thought that by putting self at the beginning it would get it but it didn't so I tried indenting it in an other way but didn't work either.

Take a look at the Python Tutorial

the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call.

Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.

So your first argument has a special meaning.

If we preserve your code (which we shouldn't), it should look like this to make it work:

  def create_canvas(void):
     get_var = void.size

If we want to follow the conventions (which we should), it shoul look like this to make it work and look pythonic:

  def create_canvas(self):
     get_var = self.size

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