should a modifying class method save itself or be explicity called after the method is called?

  • Last Update :
  • Techknowledgy :

 If you want to define an instance method, the foremost parameter of the method should always have to be self. Let us understand this with the help of example code – 

class myClass:
   def instance_method(self):
   returnInstance method is called”, self

Now, let us see what happens when we call “instance_method”: 

>>>obj = myClass() 
>>>obj.instance_method() 
('Instance method is called', <myClass instance at 1x09255d103>)

This shows that “instance_method” can access the object instance (printed as <myClass instance>) through the self parameter. What happens is that the self parameter is replaced with the instance object obj when the method is called. However, if you pass the instance object manually, you will get the same result as before: 

>>>myClass.instance_method(obj) 
('Instance method is called', <myClass instance at 1x09255d103>)

class Student: 

def __init__(self, Alex):
   self.name = Alex #name created in constructor
def get_student_name(self):
   return self.name

Let us see an example to understand it: 

class myClass:
   def show(another):
   print(“another is used in place of self”)

Suggestion : 2

An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments). This is occasionally useful to clients as well. (Note that this only works if the base class is accessible as BaseClassName in the global scope.),In the MyClass example, this will return the string 'hello world'. However, it is not necessary to call a method right away: x.f is a method object, and can be stored away and called at a later time. For example:,Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls. For example:,A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.

def scope_test():
   def do_local():
   spam = "local spam"

def do_nonlocal():
   nonlocal spam
spam = "nonlocal spam"

def do_global():
   global spam
spam = "global spam"

spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
class ClassName:
<statement-1>
   .
   .
   .
   <statement-N>
class MyClass:
   ""
"A simple example class"
""
i = 12345

def f(self):
   return 'hello world'
x = MyClass()
def __init__(self):
   self.data = []

Suggestion : 3

10/01/2021

The following example shows how to call the standard query operator OrderBy method on an array of integers. The expression in parentheses is a lambda expression. Many standard query operators take lambda expressions as parameters, but this isn't a requirement for extension methods. For more information, see Lambda Expressions.

class ExtensionMethods2 {

   static void Main() {
      int[] ints = {
         10,
         45,
         15,
         39,
         21,
         26
      };
      var result = ints.OrderBy(g => g);
      foreach(var i in result) {
         System.Console.Write(i + " ");
      }
   }
}
//Output: 10 15 21 26 39 45

The following example shows an extension method defined for the System.String class. It's defined inside a non-nested, non-generic static class:

namespace ExtensionMethods {
   public static class MyExtensions {
      public static int WordCount(this string str) {
         return str.Split(new char[] {
               ' ',
               '.',
               '?'
            },
            StringSplitOptions.RemoveEmptyEntries).Length;
      }
   }
}

The WordCount extension method can be brought into scope with this using directive:

using ExtensionMethods;

Both the MyExtensions class and the WordCount method are static, and it can be accessed like all other static members. The WordCount method can be invoked like other static methods as follows:

string s = "Hello Extension Methods";
int i = MyExtensions.WordCount(s);

In general, you'll probably be calling extension methods far more often than implementing your own. Because extension methods are called by using instance method syntax, no special knowledge is required to use them from client code. To enable extension methods for a particular type, just add a using directive for the namespace in which the methods are defined. For example, to use the standard query operators, add this using directive to your code:

using System.Linq;

Suggestion : 4

Instance variables always get a default value. If you don’t explicitly assign a value to an instance variable, or you don’t call a setter method, the instance variable still has a value!,You don’t have to initialize instance variables, because they always have a default value. Number primitives (including char) get 0, booleans get false, and object reference variables get null.,But when you don’t initialize an instance variable, what happens when you call a getter method? In other words, what is the value of an instance variable before you initialize it?,Local variables do NOT get a default value! The compiler complains if you try to use a local variable before the variable is initialized.

void play() {
   soundPlayer.playSound(title);
}
d.bark(3);
void go() {}
class ElectricGuitar {

   String brand;
   int numOfPickups;
   boolean rockStarUsesIt;

   String getBrand() {
      return brand;
   }

   void setBrand(String aBrand) {
      brand = aBrand;
   }

   int getNumOfPickups() {
      return numOfPickups;
   }

   void setNumOfPickups(int num) {
      numOfPickups = num;
   }

   boolean getRockStarUsesIt() {
      return rockStarUsesIt;
   }

   void setRockStarUsesIt(boolean yesOrNo) {
      rockStarUsesIt = yesOrNo;
   }
}
theCat.height = 27;
Dog[] pets;
pets = new Dog[7];

Suggestion : 5

Last Updated : 23 Jan, 2020,GATE Live Course 2023

Output:

Inside Parent
Inside Child

Output:

Inside Child
Inside Parent2

Output:

Inside GrandChild
Inside Parent

Output:

Inside Parent
Inside Child

Output:

Inside Parent
Inside Child

Suggestion : 6

Again, observe that inside this class, we refer to each member by just its name. Outside the class (in the Application class) we must refer to each static member by its class name followed by its member name. , Given the use of a library class, the main method in the Application class must refer to its members by using both their class name and member name: e.g., int ordinal = DateUtility.ordinalDate(month, day, year); , Here is a trivial but complete class named Application. It is defined in the anonymous package, imports a neccessary class from the course library, and has a main method that performs some trivial I/O on the console. , Let us see how to hand simulate a call to this method by using a call frame. Pay close attention to how this, the implicit parameter, is initialized by the implicit argument. Assume that we have declared

  public static int min(int a, int b) {
     if (a <= b)
        return a;
     else
        return b;
  }
1._
  public static int min(int a, int b) {
     if (a <= b)
        return a;
     else
        return b;
  }

If we wrote the statement

  System.out.println(Math.min(3, 5));
3._
  System.out.println(Math.min(3 * x + 5, y));
  System.out.println(Math.min(3 * x + 5, y));

As a syntax constraint, Java requires that expression must be compatible with the return-type specified in the method's header (either be the same, or be implicitily convertible). In a void method (or a constructor), Java requires us to discard this option altogether. Typically, expression is a literal or a variable, but sometimes it is a more general expression using operators/method calls. For example, we will see methods that include the return statements

  return true;
  return a;
  return i % divisor == 0;

Thus, we will adopt a more pragmatic approach, putting simplicity as the paramount aspect of the code that we write: if multiple return statements make a method simpler and easier to understand, use them. But be able to argue why; don't just use them because you are sloppy. I would argue, for example, that the min method defined above, which has two return statements, is simpler than the one below, which has only one return statement.

  public static int min(int a, int b) {
     int answer;
     if (a <= b)
        answer = a;
     else
        answer = b;
     return answer;
  }

In fact, this method is actually defined in the Java library as

  public static int min(int a, int b) {
     return (a <= b ? a : b);
  }
  public static boolean isLeapyear(int year) {
     return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
  }
1._
  public static boolean isLeapyear(int year) {
     return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
  }

  public static boolean isBetween(int low,
     int middle,
     int high) {
     return low <= middle && middle <= high;
  }

Suggestion : 7

Note that full_clean() will not be called automatically when you call your model’s save() method. You’ll need to call it manually when you want to run one-step model validation for your own manually created models. For example:,Note, however, that like Model.full_clean(), a model’s clean() method is not invoked when you call your model’s save() method.,All three steps are performed when you call a model’s full_clean() method.,The second step full_clean() performs is to call Model.clean(). This method should be overridden to perform custom validation on your model.

from django.db
import models

class Book(models.Model):
   title = models.CharField(max_length = 100)

@classmethod
def create(cls, title):
   book = cls(title = title)
# do something with the book
return book

book = Book.create("Pride and Prejudice")
class BookManager(models.Manager):
   def create_book(self, title):
   book = self.create(title = title)
# do something with the book
return book

class Book(models.Model):
   title = models.CharField(max_length = 100)

objects = BookManager()

book = Book.objects.create_book("Pride and Prejudice")
from django.db.models
import DEFERRED

@classmethod
def from_db(cls, db, field_names, values):
   # Default implementation of from_db()(subject to change and could # be replaced with super()).
if len(values) != len(cls._meta.concrete_fields):
   values = list(values)
values.reverse()
values = [
   values.pop() if f.attname in field_names
   else DEFERRED
   for f in cls._meta.concrete_fields
]
instance = cls( * values)
instance._state.adding = False
instance._state.db = db
# customization to store the original field values on the instance
instance._loaded_values = dict(
   zip(field_names, (value
      for value in values
      if value is not DEFERRED))
)
return instance

def save(self, * args, ** kwargs):
   # Check how the current values differ from._loaded_values.For example,
   # prevent changing the creator_id of the model.(This example doesn 't
      # support cases where 'creator_id'
      is deferred).
if not self._state.adding and(
      self.creator_id != self._loaded_values['creator_id']):
   raise ValueError("Updating the value of creator isn't allowed")
super().save( * args, ** kwargs)
>>> obj = MyModel.objects.first() >>>
   del obj.field >>>
   obj.field # Loads the field from the database
def test_update_result(self):
   obj = MyModel.objects.create(val = 1)
MyModel.objects.filter(pk = obj.pk).update(val = F('val') + 1)
# At this point obj.val is still 1, but the value in the database
# was updated to 2. The object 's updated value needs to be reloaded
# from the database.
obj.refresh_from_db()
self.assertEqual(obj.val, 2)
class ExampleModel(models.Model):
   def refresh_from_db(self, using = None, fields = None, ** kwargs):
   # fields contains the name of the deferred field to be
# loaded.
if fields is not None:
   fields = set(fields)
deferred_fields = self.get_deferred_fields()
# If any deferred field is going to be loaded
if fields.intersection(deferred_fields):
   # then load all of them
fields = fields.union(deferred_fields)
super().refresh_from_db(using, fields, ** kwargs)

Suggestion : 8

By convention, the first parameter of a method is called self. The reason for this is a little convoluted, but it is based on a useful metaphor.,Again, the object on which the method is invoked gets assigned to the first parameter, self. The second parameter, seconds gets the value 500.,The object on which the method is invoked is assigned to the first parameter, so in this case current_time is assigned to the parameter time.,Because the reverse method is a modifier, we make a copy of the list before reversing it. That way, this method doesn’t modify the list it gets as a parameter.

class Time:
   pass

def print_time(time):
   print(str(time.hours) + ":" +
      str(time.minutes) + ":" +
      str(time.seconds))
>>> current_time = Time() >>>
   current_time.hours = 9 >>>
   current_time.minutes = 14 >>>
   current_time.seconds = 30 >>>
   print_time(current_time)
class Time:
   def print_time(time):
   print(str(time.hours) + ":" +
      str(time.minutes) + ":" +
      str(time.seconds))
>>> current_time.print_time()
class Time:
   #previous method definitions here...

   def increment(self, seconds):
   self.seconds = seconds + self.seconds

while self.seconds >= 60:
   self.seconds = self.seconds - 60
self.minutes = self.minutes + 1

while self.minutes >= 60:
   self.minutes = self.minutes - 60
self.hours = self.hours + 1
current_time.increment(500)

Suggestion : 9

Every class should have a method with the special name __init__. This initializer method is automatically called whenever a new instance of Point is created. It gives the programmer the opportunity to set up the attributes required within the new instance by giving them their initial state/values. The self parameter (we could choose any other name, but self is the convention) is automatically set to reference the newly created object that needs to be initialized.,We can make our class constructor more general by placing extra parameters into the __init__ method, as shown in this example:,The combined process of “make me a new object” and “get its settings initialized to the factory default settings” is called instantiation.,The variables p and q are assigned references to two new Point objects. A function like Turtle or Point that creates a new object instance is called a constructor, and every class automatically provides a constructor function which is named the same as the class.

1
2
3
4
5
6
7
class Point:
   ""
" Point class represents and manipulates x,y coords. "
""

def __init__(self):
   ""
" Create a new point at the origin "
""
self.x = 0
self.y = 0
1
2
3
4
p = Point() # Instantiate an object of type Point
q = Point() # Make a second point

print(p.x, p.y, q.x, q.y) # Each point object has its own x and y
0 0 0 0
from turtle
import Turtle

tess = Turtle() # Instantiate objects of type Turtle
alex = Turtle()