Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python class

class Person:
    # class static variable
    person_type = "Human"

    # class constructor
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    # initialized class method
    def get_full_name(self):
        return f"{self.first_name} {self.last_name}"

    # initialized class method
    def introduce(self):
        return f"Hi. I'm {self.first_name} {self.last_name}. I'm {self.age} years old."

    # class static method
    @staticmethod
    def class_name(self):
        return 'Person'

    # class method
    @classmethod
    def create_anonymous(cls):
        return Person('John', 'Doe', 25)

    # dunder method - return class as a string when typecast to a string
    def __str__(self):
        return f"str firstname: {self.first_name} lastname: {self.last_name} age: {self.age}"

    # dunder method - return class a string then typecast to representative
    def __repr__(self):
        return f"repr firstname: {self.first_name} lastname: {self.last_name} age: {self.age}"

    # dunder method - return sum of ages when using the + operator on two Person classes
    def __add__(self, other):
        return self.age + other.age


# create a person class
bob = Person(first_name="John", last_name="Doe", age=41)

# print static method
print(Person.class_name(Person))

# print new class person
print(Person.create_anonymous().get_full_name())

# print class static method
print(Person.person_type)

# print string representation of class
print(bob)

# print representation of class
print(repr(bob))

# add Person classes ages using dunder method
print(bob + bob)
Source by codefreelance.net #
 
PREVIOUS NEXT
Tagged: #python #class
ADD COMMENT
Topic
Name
5+2 =