class & static and cls methods

This commit is contained in:
2025-08-24 20:46:15 +05:30
parent 2981454719
commit 64e8249d43

91
src/advance/class.py Normal file
View File

@ -0,0 +1,91 @@
class MyClass:
pass
person = MyClass()
class Car:
# See show_wheels method to access
wheels = 4 # class attribute shared by all cars (static variable)
# Constructor
def __init__(self, name, origin_location, price):
print("Hello")
self.name = name
self.origin_location = origin_location
# __ makes it private
self.__price = price # private attribute
# _original_cost is "internal use"
# It does not prevent access from outside the class; its just a hint to developers
self._original_cost = price
# The first parameter is always self, which refers to the instance.
def start_engine(self):
print(f"{self.name}'s Engine is starting...")
@classmethod
def show_wheels(cls):
print(f"All cars have {cls.wheels} wheels")
# The normal constructor is __init__.
# An alternate constructor is a class method that returns an instance of the class .
# Uses @ classmethod decorator.
# The first parameter is cls(the class itself).
@classmethod
def from_string(cls, string_value):
# Assume format: "Name-Origin_location-Price"
name, origin_location, price = string_value.split('-')
# create instance using main __init__
return cls(name, origin_location, price)
@classmethod
def from_dict(cls, data: dict):
# get() is dict method to get the value from dict if value is missing it gives default
return cls(data.get('name', ''), data.get('origin_location', None), data.get('price', 10_000_000),)
# toString method(dart)
def __str__(self):
return f"Car( name: {self.name}, origin_location: {self.origin_location}, price: {self.__price}, wheels: {Car.wheels} )"
@staticmethod
def car_info():
print("Cars are vehicles with wheels")
car = Car("Audi", "German", 30_000_000)
car2 = Car("Maruthi", "India", 15_000_000)
print(car.name)
print(car.origin_location)
print(car)
car.start_engine()
car2.start_engine()
print()
print("car wheels befor ==>", car.wheels)
print("car wheels befor ==>", car2.wheels)
Car.wheels = 5 # class attribute shared by all cars
print()
print("car wheels after ==>", car.wheels)
print("car wheels after ==>", car2.wheels)
print()
# print(car.__price) # Error, cannot access directly
print(car._original_cost) # Works, but intended as internal
Car.show_wheels()
car3 = Car.from_string('BMW-GERMAN-13_000_000')
print(car3)
dict_value = {
"name": "Tata",
"price": "10_000_000",
"origin_location": "india",
}
car4 = Car.from_dict(dict_value)
print(car4)
Car.car_info()