Discord Server Red Security Twitter Donation to Red Security Red Security Youtube Channel Red Security Tumblr Profile
Login or Register to Hide ads and Accessing all features on the forum

Help 

Methods, Class Methods & Static Method Example

0 Replies, 1166 Views

Methods, Class Methods & Static Methods:
          Hi guys, I found this example of the SoloLearn app in the Python Intermediate course and the author of this code is Noteve. The explanation is best I have seen on internet check this out

"""
This is a simple example of using method, classmethod, and staticmethod that I came up with.

This is made for an explanation for a comment at 'Intermediate Python' Course, OOP Module, classmethod vs staticmethod.

■ Variables used in this example ■
class :  Human
object:  h1 and h2


■ Methods defined inside the class ■
method:  desc(self)
        --> A method to introduce
            himself by telling
            us what his name is
           
static:  say_hello()
        --> A method to say 'Hello!'
       
classm:  create_human(cls, name)
        --> A costumized constructor
            to verify if name is a
            string before creating
            the object or instance.
           
           

● ● ●
NOTE:
  Please try to read each comment
  while running the program to
  understand what is happening on
  each line of code.
● ● ●
"""




class Human:

    def __init__(self, name):
        self.name = name


    def desc(self):
        """
        The function inside the class
        has `self` as its FIRST
        parameter which represents
        the object itself.
     
        ⊙ in this example,`h1` and
          `h2` are the obj
     
        We need the parameter `self`
        in order to access the
        specific attributes and
        method of the obj,
        i.e that particular Human.
     
        ⊙ try to omit the `self`
          parameter and self.name
          will be undefined
       
       
        NOTE: This can still accept
              other parameters *args
              if you want to.
        """
     
        print("My name is " + self.name )
     
     
     
    @staticmethod
    def say_hello():
        """
        staticmethod means that it
        alwayshas the same
        functionality because it does
        not depend on the object
        attributes.
     
        Unlike on the desc() method,
        we need the `self` parameter
        to access the `self.name` or
        the name of that specific
        Human
        (which in this case
        "John")
        because different objects
        will have different
        or attributes
     
        But here, we only need to
        print or say "Hello!" to the
        screen which does not
        any attributes,
        ... just "Hello!".       
     
        NOTE: This can still accept
              other parameters *args
              if you want to.
        """
     
        print("Hello!")
     
     
     
    @classmethod
    def create_human(cls, name):
        """
        Here, I used classmethod to
        create an instance of the
        class
     
        The purpose of this specific
        implemention in my example
        is to verify first if
        name is valid before creating
        that particular Human or obj.
     
        As you can see, cls
        represents the class itself.
        Hence,
        `cls(name)` is the same with
        `Human(name)` where name is
                John in this example
                   
        Then it will call the
        __init__  method to create
        the instance and its
        attributes.
     
        Finally, it will return that
        created instance to the
        variable `h1`.
     
        ● ● ●
        NOTE:
          This is useful in
          situations like this, e.g.
          to verify first
          if name is valid before
          creating.
        ● ● ●
        """
        if type(name) == str:
            return cls(name)
        else:
            print("Invalid Name!")



# Create a Human object `h1` and pass
# "John" as its  argument or `name`
# You can do it like this:
# h = Human("John")
# But for the sake of this example,
# I will use the classmethod to verify
# first if the name is string.

print("CODE: h1 = Human.create_human(\"John\")")
h1 = Human.create_human("John")

# 3.1416 is not a string or an
# Invalid name, fortunately the
# classmethod  can handle this type
# of situation
print("\n\nCODE: h2 = Human.create_human(3.1416)")
h2 = Human.create_human(3.1416)


# Call the desc() method using the
# object `h1`. By using the object to call
# a method, the `self` is already passed.
print("\n\nCODE: h1.desc()")
h1.desc()

# h1.desc() is similar to this code.a
# We passed the `h1` as the `self`
# to the Human.desc() method.
print("\n\nCODE: Human.desc(h1)")
Human.desc(h1)


# Call the staticmethod say_hello()
# using the object 'h1'
print("\n\nCODE: h1.say_hello()")
h1.say_hello()

# Call the staticmethod say_hello
# using the Human class itself.
# We don't need the obj argument
# because we only need to say hello
# and that does not require any
# object or attribute
print("\n\nCODE: Human.say_hello()")
Human.say_hello()
Love me like you do Heart

Possibly Related Threads…
Thread Author Replies Views Last Post
  Tutorial Python 3.5: Class Methods Covid-19 0 1,725 05-29-2022, 01:07 PM
Last Post: Covid-19



Users browsing this thread: 1 Guest(s)