python methods code example

Example 1: list methods python

list.append(x) # append x to end of list
list.extend(iterable) # append all elements of iterable to list
list.insert(i, x) # insert x at index i
list.remove(x) # remove first occurance of x from list
list.pop([i]) # pop element at index i (defaults to end of list)
list.clear() # delete all elements from the list
list.index(x[, start[, end]]) # return index of element x
list.count(x) # return number of occurances of x in list
list.reverse() # reverse elements of list in-place (no return)
list.sort(key=None, reverse=False) # sort list in-place
list.copy() # return a shallow copy of the list

Example 2: how to make a class in python

class Person:
  def __init__(self, _name, _age):
    self.name = _name
    self.age = _age
   
  def sayHi(self):
    print('Hello, my name is ' + self.name + ' and I am ' + self.age + ' years old!')
    
p1 = Person('Bob', 25)
p1.sayHi() # Prints: Hello, my name is Bob and I am 25 years old!

Example 3: what is method in python

It's a function which is a member of a class:

Example 4: methods in python

#Objects can also contain methods. Methods in objects are functions that belong to the object.
#Let us create a method in the Person class:

class Person:
  
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def myfunc(self): # This is a method
    print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

Example 5: java methods

public class MyClass {
  static int myMethod(int x) {
    return 5 + x;
  }

  public static void main(String[] args) {
    System.out.println(myMethod(3));
  }
}
// Returns 8

Tags:

Java Example