Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Python classes and objects

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

    def greet(self, person_to_greet):
        # person_to_greet will be another Person object
        print(f"Hey {person_to_greet.name}, nice to meet you I'm {self.name}")

    def ask_age(self, ask_from):
        print(f"{self.name}: {ask_from.name}, How old are you?")
        print(f"{ask_from.name}: i am {ask_from.age}")


# Creating a person object
tom = Person("Tom", 50, "Male")

# we can also create an object with keyword arguments
jack = Person(name="Jack", age=19, gender="Male")

# Here we call the greet method of tom, and we pass the Jack Person Object Created above
tom.greet(jack)

# if we call the greet method of jack and pass the Tom person object, then jack greets tom
jack.greet(tom)

# Here Jack will ask age of tom, and tom will reply with his age
jack.ask_age(tom)
Source by pydoc.pages.taltech.ee #
 
PREVIOUS NEXT
Tagged: #Python #classes #objects
ADD COMMENT
Topic
Name
8+6 =