Python class self reference

Class variable reference itself?

I am new to coding period (3-ish weeks) and have been building and rebuilding a RPG to help teach myself the principles that I have been learning. However, I seem to be stuck on one specific aspect of Python classes. A class variable I have created for my worldLocation class reads as such where the NORTH , EAST , SOUTH , WEST all reference strings:

WHITEROOM = worldLocation('A Plain White Room', '. \n\nWhere are you?\n\n' 'All around you is white. \n\n' '. only white. ', [ROCK.GROUNDDESC], [RAT.NAME], ) 

But I want it to instead read like this, where each of the instance variables references the class variable itself:

WHITEROOM = worldLocation('A Plain White Room', '. \n\nWhere are you?\n\n' 'All around you is white. \n\n' '. only white. ', [ROCK.GROUNDDESC], [RAT.NAME], ) 

However, every time I attempt to change it to the latter, I receive an undefined name WHITEROOM error. What am I doing wrong or missing? The class code is as follows:

class worldLocation(object): def __init__(self, NAME, DESC, GROUND, ENEMIES, DIRECTIONS): self.NAME = NAME self.DESC = DESC self.GROUND = GROUND self.ENEMIES = ENEMIES self.DIRECTIONS = DIRECTIONS 

3 Answers 3

The code you want to use is trying to reference the instance in a dictionary being passed as argument to __init__() before it exists. That’s not feasible (and arguably really reasonable if you think about it).

Читайте также:  Java suppress warning unchecked cast

However, you can workaround the issue by creating a special value that the class initializer __init__() method can check for and fix-up the data being passed.

Below is code illustrating what I mean. Note I’ve added some scaffolding at the beginning to make it runnable for testing purposes.

#### Some scaffolding for testing. NORTH, SOUTH, EAST, WEST = 'NORTH SOUTH EAST WEST'.split() class ROCK: GROUNDDESC = 'ground desc' class RAT: NAME = 'Ricky' #### class WorldLocation: THIS = object() # A unique value. def __init__(self, NAME, DESC, GROUND, ENEMIES, DIRECTIONS): self.NAME = NAME self.DESC = DESC self.GROUND = GROUND self.ENEMIES = ENEMIES # Replace any values in DIRECTIONS dictionary argument that refer to the # instance being created (as designated by them being the class # attribute THIS). self.DIRECTIONS = WHITEROOM = WorldLocation('A Plain White Room', '. \n\nWhere are you?\n\n' 'All around you is white. \n\n' '. only white. ', [ROCK.GROUNDDESC], [RAT.NAME], ) # Show that it works. from pprint import pprint print(f'id(WHITEROOM): 0x\n') pprint(vars(WHITEROOM)) 
id(WHITEROOM): 0x010d0390 , 'NORTH': , 'SOUTH': , 'WEST': >, 'ENEMIES': ['Ricky'], 'GROUND': ['ground desc'], 'NAME': 'A Plain White Room'> 

Источник

Python Self

Python Certification Course: Master the essentials

In Python, the self parameter refers to the instance of a class, allowing access to its members and methods, as well as facilitating the initialization of new members. self acts as a reference to the instance itself and is automatically passed by Python when calling object methods, and we can use another name for the parameter instead of self .

Introduction

Suppose you have a class named as a student with three instance variables student_name , age , and marks . Now you want to access these members in a class function. What should you do? You cannot call these members directly. This will cause an error because Python will search these variables outside the class instead of the class. Now how can we solve this problem? The answer is using a self word (a reference to class). We pass the self as an argument in the method and access these members, or also we can manipulate the state of these members. Let’s dive deep and understand some characteristics or properties of the self.

What is Self in Python?

The self is an instance of the class; by using the self , we can access or manipulate the state of the instance members of the class. Also, we can create new instance members with the help of self . The self is mostly used for initializing the instance members of the class.

Syntax

The self is passed as an argument in the method of the class, and by default, it is compulsory to pass the reference of the class in all the methods of the class.

In the above program, we pass the self in the method and access the class instance variable, i.e., a.

What is the Use of Self in Python?

self in python example 2

Python doesn’t provide any operator for accessing the instance members of the user-defined class but allows the user to pass the instance of a class, i.e., self, as an argument to the method so that the user can access the instance variables.

In the above program, we are accessing the instance variable with the help of the self word and without using the self.

Why Self is Defined Explicitly in Python?

According to the zen of Python «Explicit is better than implicit» . Because explicitly writing the code(clearly defining the state of something even if it is obvious) helps to increase the readability of the code. In a Python programming language, we have to pass the reference of the class (using the self word) as an argument in every method of the class, but why do we have to send the class reference, i.e., self, to all the methods? Can we use the self as a parameter?

In the above example, when we call the method of the class Scaler using an object, i.e. a.hello(1) , Internally during the calling of this method, the Python language converts the calling to class.hello(a(object), number) . This is why we have to first argument as a reference (self word) in the method, and also, this is the reason self is defined explicitly.

Python Class self Constructor

A class constructor is a special method that is automatically called when an object of a class is created. The constructor method is defined using the __init__() function within a class.

The self parameter in the constructor represents the instance of the object being created, just like in any other method. The self parameter allows you to access and manipulate the attributes and methods of the object within the class.

Here’s an example of a Python class with a constructor:

The code demonstrates a Python class called MyClass with two methods: a constructor ( __init__ ) and a display method ( display_info ).

  • The constructor initializes the object’s attributes using the provided name and age parameters.
  • An instance of MyClass is created with the arguments «John» and 25, and Python automatically handles the self parameter.
  • The display_info method is called, printing the stored name and age attributes.

Is Self in Python a Keyword?

The self word is not a keyword in Python. For the sake easiest naming convention, we often use the self word in place of the other word, and it is advisable to use the self word instead of the other word because one of the major reasons for this is most of the internal Python libraries used word self to represent the reference of the object. So to reduce the conflict between the programmers and the inbuilt libraries, we often use the self word.

In the above program, we used another word instead of self to represent the object state, i.e., hello , which proves self is not a keyword; we can use any other name according to our choice :).

How Can We Skip Self in Python?

Now, Suppose you want to skip the self word as a parameter in the class methods. What should you do? We can skip self as an argument in the method by adding the @staticmethod decorator on the method, which makes the method static. The static methods don’t need the reference of the class. A static method cannot access or modify the class members. We generally use static methods when we write some operations that are not supposed to be changed in the future, like some fixed arithmetic calculations.

Conclusion

  • Self is used for accessing the instance members of the class.
  • Self is not a keyword in Python.
  • We have to pass self as a parameter in every class method by default.
  • We can skip the self as a parameter in a method by using the @staticmethod decorator on the method of the class.
  • Self is always defined explicitly.

The most common application of the self is it helps to call the instance member or method in any method. For example, we can call any method in the body of another method any number of times with our help of self.

See Also

Источник

self in Python class

In this tutorial, we are going to learn about the self in Python. You must be familiar with it if you are working with Python. We will see some interesting things about.

Note − self is not a keyword in Python.

Let’s start with the most common usage of self in Python.

We’ll use self in classes to represent the instance of an object. We can create multiple of a class and each instance will have different values. And self helps us to get those property values within the class instance. Let’s see ane example.

Example

# class class Laptop: # init method def __init__(self, company, model): # self self.company = company self.model = model

We are defining the properties of a class as self.[something]. So, whenever we create an instance of the class, the self will refer to a different instance from which we are accessing class properties or methods.

Now, let create two instances of the class Laptop and see how the self works.

Example

# class class Laptop: # init method def __init__(self, company, model): # self self.company = company self.model = model # creating instances for the class Laptop laptop_one = Laptop('Lenovo', 'ideapad320') laptop_two = Laptop('Dell', 'inspiron 7000') # printing the properties of the instances print(f"Laptop One: ") print(f"Laptop Two: ")

Output

If you run the above code, then you will get the following result.

Laptop One: Lenovo Laptop Two: Dell

We got two different names for the same property. Let’s see some details behind it.

Python sends a reference to the instance by default while accessing it methods or And the reference is captured in self. So, for each instance the reference is different. And we will get the respective instance properties.

We know that the self is not a keyword of Python. It’s more of like an argument that you don’t need to send while accessing any property or method of an instance.

Python will automatically send a reference to the instance for you. We can capture the of the instance with any variable name. Run the following code and see the output.

Example

import inspect # class class Laptop: # init method def __init__(other_than_self, company, model, colors): # self not really other_than_self.company = company other_than_self.model = model other_than_self.colors_available = colors # method def is_laptop_available(not_self_but_still_self, color): # return whether a laptop in specified color is available or not return color in not_self_but_still_self.colors_available # creating an instance to the class laptop = Laptop('Dell', 'inspiron 7000', ['Silver', 'Black']) # invoking the is_laptop_available method withour color keyword print("Available") if laptop.is_laptop_available('Silver') else print("Not available") print("Available") if laptop.is_laptop_available('White') else print("Not available")

Output

If you run the above code, then you will get the following result.

We have changed the name self to something else. But still, it works as it before. There is no difference. So, self is not a keyword. And moreover, we can change the self to whatever we like to have. It’s more like an argument.

Note − best practice is to use the self.. It’s a standard that every Python programmer follows

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Источник

Оцените статью