ข้ามไปที่เนื้อหาหลัก

OOP W

python object oriented 

Student Class

Attributes

Student ID

First name

Last name

Credits

GPA

Behaviors

Enroll()

Take_examination()



class Student:

    def __init__(self, student_id, first_name, last_name):

        self.student_id = student_id

        self.first_name = first_name

        self.last_name = last_name

        self.credits = 0

        self.GPA = 0.0


    def enroll(self, credits):

        self.credits += credits


    def take_examination(self, grade_points):

        # Perform examination logic and calculate GPA based on grades

        # For simplicity, let's assume grade_points are added to GPA directly

        total_points = self.GPA * self.credits

        self.credits += 1  # Assuming 1 credit for the examination

        total_points += grade_points

        self.GPA = total_points / self.credits


# Example usage:

student1 = Student("001", "John", "Doe")

student1.enroll(3)  # Enroll in 3 credits

student1.take_examination(4)  # Take an examination with grade points 4


print(f"{student1.first_name} {student1.last_name} - Student ID: {student1.student_id}")

print(f"Credits: {student1.credits}")

print(f"GPA: {student1.GPA}")


2. 

class Student:

    def __init__(self, student_id, first_name, last_name, credits=0, gpa=0.0):

        self.student_id = student_id

        self.first_name = first_name

        self.last_name = last_name

        self.credits = credits

        self.gpa = gpa


    def enroll(self, course_credits):

        self.credits += course_credits


    def take_examination(self, grade_points):

        # Calculate GPA based on the new grade

        total_grade_points = self.gpa * self.credits

        total_grade_points += grade_points

        self.credits += 1  # Assuming one course credit for the exam

        self.gpa = total_grade_points / self.credits


    def display_info(self):

        print(f"Student ID: {self.student_id}")

        print(f"Name: {self.first_name} {self.last_name}")

        print(f"Credits: {self.credits}")

        print(f"GPA: {self.gpa:.2f}")



# Example usage:

student1 = Student(1, "John", "Doe")

student1.enroll(3)  # Enroll in courses worth 3 credits

student1.take_examination(4.0)  # Grade points earned in an exam


student1.display_info()  # Display student information







# Encapsulation example

class Car:

    def __init__(self, brand, mileage):

        self.__brand = brand  # Private attribute

        self.mileage = mileage


    def get_brand(self):

        return self.__brand  # Accessing private attribute through a method


    def set_brand(self, new_brand):

        self.__brand = new_brand  # Modifying private attribute through a method



# Inheritance example

class ElectricCar(Car):  # Inheriting from the Car class

    def __init__(self, brand, mileage, battery_capacity):

        super().__init__(brand, mileage)  # Calling the base class constructor

        self.battery_capacity = battery_capacity


    def display_info(self):

        print(f"Brand: {self.get_brand()}")  # Accessing the base class method

        print(f"Mileage: {self.mileage}")

        print(f"Battery Capacity: {self.battery_capacity}")



# Polymorphism example

class Pet:

    def make_sound(self):

        pass  # Abstract method


class Dog(Pet):

    def make_sound(self):

        print("Woof!")


class Cat(Pet):

    def make_sound(self):

        print("Meow!")


# Example usage

# Encapsulation

car = Car("Toyota", 50000)

print(car.get_brand())  # Accessing private attribute through a method

car.set_brand("Honda")  # Modifying private attribute through a method

print(car.get_brand())


# Inheritance

electric_car = ElectricCar("Tesla", 20000, "75 kWh")

electric_car.display_info()


# Polymorphism

pets = [Dog(), Cat()]

for pet in pets:

    pet.make_sound()  # Calling the overridden method





Encapsulation: Using private attributes and public methods to control access to the class members.

Inheritance: Creating a derived class that inherits attributes and methods from a base class.

Polymorphism: Implementing a method in the derived class that overrides a method in the base class.


ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

OOPT01

 Lists: Lists are ordered collections that can contain elements of different types. They are mutable, meaning you can change their elements. Example: python Copy code my_list = [1, 2, "apple", True] my_list.append(5)  # Adding an element print(my_list[2])  # Accessing an element by index my_list.remove("apple")  # Removing an element print(my_list)  # Printing the modified list Dictionary: Dictionaries are unordered collections of key-value pairs. They use keys to access their associated values and are mutable. Example: python Copy code my_dict = {"name": "Alice", "age": 25, "city": "New York"} print(my_dict["age"])  # Accessing value by key my_dict["occupation"] = "Engineer"  # Adding a new key-value pair del my_dict["city"]  # Deleting a key-value pair print(my_dict)  # Printing the modified dictionary Ranges: Ranges are sequences of numbers used for iterating over a sequence...

Object Final

 Final Examination OBJECT You will be given the "project name" and django project name. Inheritance 1 question Polymorphism 1 question (main.py) Django database 1 question Rest API → List items 1 question Rest API → Item detail 1 question Rest API → Transaction 1 question (Wallet App) ----------------------------------------------------------------------------------------------------------------------------- pip install django django-admin startproject mysite_project py manage.py startapp catalog_app  Create the database models in terminal py manage.py makemigrations py manage.py migrate py manage.py createsuperuser Rest API pip install djangorestframework pip install markdown       pip install django-filter pip install virtualenv --------------------------------------------------------------------------------------------------------------------------- พยายามติดตั้ง  py manage.py makemigrations py manage.py migrate ทุกครั้งหลังจาก เปลี่ยนรูปแบบโค้ด ตัว...

OPPTH

 https://github.com/kongruksiamza/python-oop