」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Python OOPS 基礎

Python OOPS 基礎

發佈於2024-11-03
瀏覽:305

In real world everything is Object and every object have 2 things behaviour and attribute. Attribute contains data stored in variable and behaviour is defined as method which is nothing but functions(what's needs to be done)

Imagine there is some kind of phone company manufacturing phone but designed once but created multiple handset. Here design or blueprint is a class and object is a real stuff or entity or instance of class.

class Computer:
    def config(self):
        print("i5, 15gb, 1Tb")

comp1=Computer()
Computer.config()


Output:
D:\Testing Document Sample>C:/Python312/python.exe "d:/Testing Document Sample/calc.py"
Traceback (most recent call last):
  File "d:\Testing Document Sample\calc.py", line 7, in 
    Computer.config()
TypeError: Computer.config() missing 1 required positional argument: 'self'

one class have multiple object. this config method will change it's behaviour based on it's object, because different object has different behaviour. If I am calling config, for which object I am calling, like if I say "hey walk" for which object I am calling.
So I have to mention "Hey! Ravi walk" , "Hey! Mukesh walk"
In the same way when I am calling the Computer.config we must say for which object we are talking about, and I am talking about comp1, which means " Hey! I want the config for comp1"
thus writing the update code and run

class Computer:
    def config(self):
        print("i5, 15gb, 1Tb")

comp1=Computer()
Computer.config(comp1)


Output:
D:\Testing Document Sample>C:/Python312/python.exe "d:/Testing Document Sample/calc.py"
i5, 15gb, 1Tb

Here we are calling Computer.config(comp1) where comp1 is passed as arguement to the parameter self under config method. So from there self came up, self is the paramter to pass the object.

If I want to call config for comp2 then. If I run this code we get the same output twice, as we are not changing data as per different object.

class Computer:
    def config(self):
        print("i5, 15gb, 1Tb")

comp1=Computer()
comp2=Computer()
Computer.config(comp1)
Computer.config(comp2)


Output:
D:\Testing Document Sample>C:/Python312/python.exe "d:/Testing Document Sample/calc.py"
i5, 15gb, 1Tb
i5, 15gb, 1Tb

Another to call the method, the first 2 is for Computer.config(comp1) and 2nd two is for comp1.config()

class Computer:
    def config(self):
        print("i5, 15gb, 1Tb")

comp1=Computer()
comp2=Computer()
Computer.config(comp1)
Computer.config(comp2)
comp1.config()
comp2.config()

Output:
D:\Testing Document Sample>C:/Python312/python.exe "d:/Testing Document Sample/calc.py"
i5, 15gb, 1Tb
i5, 15gb, 1Tb
i5, 15gb, 1Tb
i5, 15gb, 1Tb

Now for behind this what's happening. when we use these, as already object is reference with class at time of creation. So behind this scene, config will take comp1/comp2 as arguement and pass to parameter as self. thus most of the code we see this below type of syntax not the old one.

comp1.config()
comp2.config()

ctrl click bit_length for below example. calling bit_length it will not passing it. so this 'a' is an object it act as arguement and pass it as parameter to self.

eg:
a=3
a.bit_length()

So this is the way that we can create object

Let move further, suppose I want to create different cpu and ram configuration, which require 2 variables, which is cpu and ram. so how to find that.
That's where the picture came special method and variable having underscores (method/variable)

below example as we call config twice the output under init shows twice because we have created 2 objects, which automatically calls the init

class Computer:
    def __init__(self):         //  act as contructor which get called when object created.
        print("initalize init")  
    def config(self):
        print("i5, 15gb, 1Tb")

comp1=Computer()
comp2=Computer()

comp1.config()
comp2.config()


Output:
D:\Testing Document Sample>C:/Python312/python.exe "d:/Testing Document Sample/calc.py"
initalize init
initalize init
i5, 15gb, 1Tb
i5, 15gb, 1Tb

Now Supppose I want to get values based on cpu and ram with respect to object comp1/comp2 so we need to pass the argument mentioning cpu and ram and create variable in init method.
Now since I want cpu and ram values are need to be part of object thus so here is the code for below.

class Computer:
    def __init__(self,cpu,ram):    // self represent object name thus having 3 parameter (self=comp1,cpu='i5',ram=16)
        self.cpu = cpu                // as we need to assign value to object thus using self.cpu=cpu as self is object 
        self.ram = ram
    def config(self):
        print("config is", self.cpu, self.ram)      // Since this CPU and ram is belongs to object thus using self.cpu/self.ram

comp1=Computer('i5',16)
comp2=Computer('Ryzen 3',8)    // passing two arguments to __init__ method

comp1.config()
comp2.config()


Output:
D:\Testing Document Sample>C:/Python312/python.exe "d:/Testing Document Sample/calc.py"
config is i5 16
config is Ryzen 3 8

Thus for the above the data and methods work together i.e binding data with every method so one object has it's own method and has it's own variable.

Comp1 is object or referring to an cbject. I our system we have a special memory called Heap memory. Heap memory will contain all objects. so I might have some address in heap memory the way to print the address is :

class computer:
    pass
c1=computer()

print(id(c1))

Output:
D:\Testing Document Sample>C:/Python312/python.exe "d:/Testing Document Sample/demo.py"
2509775964640     // this is an address

What will be size of object?
It's depend upon the size of variable and number of variable

who allocate the memory to object ?
Constructor

we can also change the value of one object from different object

Example:

class computer:
    def __init__(self):
        self.name = "navin"
        self.age = 28

c1=computer()
c2=computer()

c1.name="rashi"
c2.age= 12

print (c1.name)
print (c2.name)
print (c1.age)
print (c2.age)

Output:
D:\Testing Document Sample>C:/Python312/python.exe "d:/Testing Document Sample/demo.py"
rashi
navin
28   
12

in the above code we can not only assign the different values to object explicitly but can change it also

Why do we need this self?
To explain that lets take one more method called update which is used to update the age
When update is called it will update the age in class computer, but here is catch we have two objects which value needs to be changed, as we called it we have not passed any arguement c1 or c2.
So when calling update how do pointer know which object we are calling about weather c1 age or c2 age and that's where we are using self is directing to c1 and c2 based on calling by object. If we are using c1.update then in the bracket it will pass c1, then self will assign to c1, that's the important of self which is referring to the object.

class computer:
    def __init__(self):
        self.name = "navin"
        self.age = 28

    def update(self):
        self.age = 30


c1=computer()
c2=computer()

c1.name="rashi"
c2.age= 12

c1.update()      // this calls the update method. In the 

print (c1.name)
print (c2.name)
print (c1.age)
print (c2.age)


Output:
D:\Testing Document Sample>C:/Python312/python.exe "d:/Testing Document Sample/demo.py"
rashi
navin
30
12

Let's compare the object for above: In below python don't know how to compare object. thus In this I will use seperate function to do that.

class computer:
    def __init__(self):
        self.name = "navin"
        self.age = 28

#   def update(self):
#      self.age = 30

    def compare(self,other):     // here c1 becomes self as object used to call and c2 become others passed as arguement
        if self.age==other.age:
            return true
        else:
            return false

c1=computer()
c1.age=30
c2=computer()

# if c1==c2:            // I don't want to compare address but want to compare their values(age) name doesn't matter

if c1.compare(c2):     // Since it's not an in build function thus we need to create it 
    print("They are same")

else:
    print("They are Different")

#c1.update()

print (c1.age)
print (c2.age)


Output:
D:\Testing Document Sample>C:/Python312/python.exe "d:/Testing Document Sample/demo.py"
They are Different
30
28

Types of variable in OOPS

  1. Instance Variables (Object Attributes)

Definition: These variables are tied to a specific instance of a class. Each object of the class can have different values for these variables.
Scope: They are accessible only within the instance they belong to, not across all instances of the class.
How to Define: Defined inside the constructor method (init()) and are prefixed with self.

Example:

class Car:
    def __init__(self, model, color):
        self.model = model  # Instance variable
        self.color = color  # Instance variable

car1 = Car("Tesla", "Red")
car2 = Car("BMW", "Blue")

print(car1.model)  # Output: Tesla
print(car2.model)  # Output: BMW

Here, model and color are instance variables that are specific to each instance of the Car class.
  1. Class Variables (Static Variables)

Definition: These are variables that are shared across all instances of the class. They are defined inside the class but outside of any instance methods.
Scope: They belong to the class itself and not to individual objects. Changes made to class variables affect all instances of the class.
How to Define: Declared within the class, but outside of any method. They are accessed using the class name or through any instance of the class.

Example:

class Car:
    wheels = 4  # Class variable

    def __init__(self, model, color):
        self.model = model
        self.color = color

car1 = Car("Tesla", "Red")
car2 = Car("BMW", "Blue")

print(Car.wheels)  # Output: 4 (Accessed through class)
print(car1.wheels)  # Output: 4 (Accessed through an instance)

Here, wheels is a class variable shared by all instances of the Car class. Both car1 and car2 will have access to this variable.
  1. Instance Methods (Method Variables)

Definition: Variables declared inside instance methods (other than init) are method variables, and they are local to that specific method.
Scope: These variables are created and exist only within the method where they are defined. They are not accessible outside the method.
How to Define: Defined inside any method of a class using standard variable declaration without self.

Example:

class Car:
    def display_info(self):
        speed = 120  # Method variable
        print(f"Speed is {speed}")

car1 = Car()
car1.display_info()  # Output: Speed is 120

Here, speed is a method variable and is local to the display_info() method. It cannot be accessed outside this method.
  1. Static Methods Variables

Definition: Variables defined inside static methods are local to that method, similar to instance methods. Static methods don’t have access to instance (self) or class variables unless passed explicitly.
Scope: Local to the static method.
How to Define: Defined inside a static method, typically declared with the @staticmethod decorator.

Example:

class Car:
    wheels = 4  # Class variable

    @staticmethod
    def show_description():
        description = "This is a car"  # Static method variable
        print(description)

Car.show_description()  # Output: This is a car

Here, description is a variable local to the static method show_description() and cannot be accessed outside this method.
  1. Class Methods Variables

Definition: Variables defined inside class methods are similar to static method variables, but class methods can access and modify class variables. Class methods are defined using the @classmethod decorator.
Scope: Variables are local to the class method, but the method has access to class variables via the cls parameter.
How to Define: Declared within class methods, typically with the @classmethod decorator.

Example:

class Car:
    wheels = 4  # Class variable

    @classmethod
    def set_wheels(cls, count):
        cls.wheels = count  # Class method variable

Car.set_wheels(6)
print(Car.wheels)  # Output: 6

Here, count is a variable within the class method set_wheels, and the method can access and modify the class variable wheels.

Key Difference :

  1. Instance Variables

Definition: Variables that are unique to each object (instance) of a class.
Scope: Available only within the instance they belong to.
Access: Accessed via self (i.e., self.variable_name).
Storage: Stored within each object; each instance has its own copy of instance variables.
Lifecycle: Created when an object is instantiated and destroyed when the object is deleted.
Modification: Each object can have its own unique values for instance variables.
Key Point: Instance variables are unique to each instance. For example, different Car objects can have different model and color.

  1. Class Variables

Definition: Variables that are shared across all instances of a class.
Scope: Belongs to the class itself and is shared by all instances.
Access: Accessed using ClassName.variable_name or via instances (though the preferred way is through the class name).
Storage: Stored in the class, not in the individual object instances.
Lifecycle: Created when the class is defined and exists for the lifetime of the class.
Modification: Modifying a class variable through the class affects all instances, whereas modifying it through an instance creates a new instance variable for that particular object.
Key Point: Class variables are shared across all instances. If wheels is changed through the class, it affects all instances unless overridden at the instance level.

  1. Method Variables (Local Variables)

Definition: Variables defined inside a method, and they are local to that method.
Scope: Available only within the method where they are defined.
Access: Can only be accessed within the method; not accessible outside the method or across instances.
Storage: Stored temporarily in the method call stack and are discarded once the method execution finishes.
Lifecycle: Created when the method is called and destroyed once the method finishes execution.
Modification: Each method call gets a fresh set of method variables.
Key Point: Method variables are local to the method and do not persist beyond the method's execution.

  1. Static Variables (Variables in Static Methods)

Definition: Variables defined inside a static method, local to the method itself, similar to method variables.
Scope: Confined to the static method where they are defined.
Access: Static methods do not have access to class or instance variables unless they are passed as arguments.
Storage: Stored temporarily during the execution of the static method.
Lifecycle: Created when the static method is called and destroyed once it finishes execution.
Modification: Modifying static method variables only affects that specific method execution.
Key Point: Static method variables are local to the static method and do not interact with class or instance variables unless explicitly passed.

Python OOPS basic


Types of Methods in oops:

  1. Instance Methods:

Definition: Instance methods are the most common type of method in a class. They operate on instances of the class (i.e., objects) and can access or modify object attributes.
How to Define: Instance methods must have self as their first parameter, which refers to the instance of the class. They can access both instance variables and class variables.
Use Case: These methods are used to manipulate object-specific data.

Example:

class Car:
    def __init__(self, model, color):
        self.model = model  # Instance variable
        self.color = color  # Instance variable

    def display_info(self):  # Instance method
        print(f"Car model: {self.model}, Color: {self.color}")

car1 = Car("Tesla", "Red")
car1.display_info()  # Output: Car model: Tesla, Color: Red

Here, display_info is an instance method that operates on the instance car1 and accesses its instance variables (model and color).
  1. Class Methods

Definition: Class methods are methods that operate on the class itself rather than on instances of the class. They can access or modify class variables but cannot modify instance variables.
How to Define: Class methods are defined using the @classmethod decorator, and they take cls as their first parameter, which refers to the class itself.
Use Case: These methods are used to work with class-level data and can be called without creating an instance of the class.

Example
class Car:
    wheels = 4  # Class variable

    @classmethod
    def change_wheels(cls, count):  # Class method
        cls.wheels = count

Car.change_wheels(6)
print(Car.wheels)  # Output: 6

In this example, change_wheels is a class method that modifies the class variable wheels and can be called on the class itself, not on individual objects.
  1. Static Methods:

Definition: Static methods are methods that don’t operate on instances or the class itself. They do not take self or cls as their first parameter and cannot modify object state or class state. Static methods behave like regular functions but are bound to a class for organizational purposes.
How to Define: Static methods are defined using the @staticmethod decorator.
Use Case: Static methods are used when you need a function that logically belongs to the class but doesn’t need to access or modify any class or instance variables.

Example:

class Car:
    @staticmethod
    def is_motorized():  # Static method
        return True

print(Car.is_motorized())  # Output: True

Here, is_motorized is a static method that doesn’t rely on any class or instance data and can be called directly on the class.

Key Differences:

Instance Methods:
Access both instance and class variables.
The self parameter allows access to object-specific data.

Class Methods:
Access only class variables.
The cls parameter allows access to class-level data and can modify it.

Static Methods:
Don’t access or modify class or instance variables.
Behave like regular functions, but are logically grouped inside a class.

Python OOPS basic


版本聲明 本文轉載於:https://dev.to/indrasen_9d014cf224a46c4a/python-oops-basic-24aa?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何在 React 中使用上下文
    如何在 React 中使用上下文
    欢迎回来,朋友们!
 今天我们将回顾名为 useContext 的 React Hook 的基础知识。 useContext 是一个强大的工具,它比 useState 更进一步,创建了一个类似全局的 State,可以将信息传递给子组件和孙组件,而无需直接传递 props。
 但我有点超前了。
如果你...
    程式設計 發佈於2024-11-03
  • JavaScript 可以修改 PHP 會話變數嗎?
    JavaScript 可以修改 PHP 會話變數嗎?
    使用 JavaScript 設定 PHP 會話變數你可以使用 JavaScript 操作 PHP 會話變數嗎? 是的,您可以透過 AJAX 請求使用 JavaScript 設定 PHP 會話變數。 操作方法如下:JavaScript 程式碼:jQuery('#div_session_write')....
    程式設計 發佈於2024-11-03
  • Babel 6 修改後的預設導出行為有何影響解決方法?
    Babel 6 修改後的預設導出行為有何影響解決方法?
    Babel 6 修改後的預設匯出行為:從方便到語意一致性的轉變在一項突破性的改變中, Babel 6 修改了其方法導出預設值,引入從先前受CommonJS 啟發的行為到嚴格的ES6 原則的轉變。這項變化為開發者帶來了機會和挑戰。 先前,Babel 在預設導出聲明中添加了一行“module.expor...
    程式設計 發佈於2024-11-03
  • 如何識別資料框中具有部分字串匹配的列?
    如何識別資料框中具有部分字串匹配的列?
    識別名稱中包含部分字串的列在資料框中,您的任務是查找名稱部分與特定字串。與精確匹配不同,要求是識別包含字串「spike」但可能在其之前或之後包含其他字元的列,例如「spike-2」、「hey spike」或「spiked-in」。 為了實現這一點,我們可以利用循環來迭代資料框的列名稱。在此循環中,...
    程式設計 發佈於2024-11-03
  • 用一個簡單的屬性來加速你的 CSS
    用一個簡單的屬性來加速你的 CSS
    您知道嗎,您可以透過使用 all: unset; 來大幅縮小 CSS 檔案大小?這會重設元素上的所有屬性,一次清除所有繼承的樣式,使您的 CSS 更精簡且更易於管理。 試試看一下,看看您的程式碼變得多麼乾淨!如何管理繼承的樣式?
    程式設計 發佈於2024-11-03
  • TypeScript 冒險與類型挑戰 – Day Pick
    TypeScript 冒險與類型挑戰 – Day Pick
    大家好。 我正在解決類型挑戰,以更深入地研究 TypeScript。 今天,我想分享一下我對Pick的了解。 - 挑戰 - interface Todo { title: string description: string completed: boolean }...
    程式設計 發佈於2024-11-03
  • 如何擴展 JavaScript 中的內建錯誤物件?
    如何擴展 JavaScript 中的內建錯誤物件?
    擴充 JavaScript 中的 Error要擴充 JavaScript 中的內建 Error 對象,您可以使用 extends 關鍵字定義 Error 的子類別。這允許您使用附加屬性或方法建立自訂錯誤。 在 ES6 中,您可以定義自訂錯誤類,如下所示:class MyError extends E...
    程式設計 發佈於2024-11-03
  • 將測試集中在網域上。 PHPUnit 範例
    將測試集中在網域上。 PHPUnit 範例
    介紹 很多時候,開發人員嘗試測試 100%(或幾乎 100%)的程式碼。顯然,這是每個團隊應該為他們的專案達到的目標,但從我的角度來看,只應該完全測試整個程式碼的一部分:您的網域。 域基本上是程式碼中定義項目實際功能的部分。例如,當您將實體持久保存到資料庫時,您的網域不負責將其持...
    程式設計 發佈於2024-11-03
  • 如何使用 SQL 搜尋列中的多個值?
    如何使用 SQL 搜尋列中的多個值?
    使用 SQL 在列中搜尋多個值建立搜尋機制時,通常需要在同一列中搜尋多個值場地。例如,假設您有一個搜尋字串,例如“Sony TV with FullHD support”,並且想要使用該字串查詢資料庫,將其分解為單字。 透過利用 IN 或 LIKE 運算符,您可以實現此功能。 使用 IN 運算子IN...
    程式設計 發佈於2024-11-03
  • 如何安全地從 Windows 登錄讀取值:逐步指南
    如何安全地從 Windows 登錄讀取值:逐步指南
    如何安全地從Windows 註冊表讀取值檢測登錄項目是否存在確定登錄項目是否存在: LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey); if (lRes...
    程式設計 發佈於2024-11-03
  • Staat原始碼中的useBoundStoreWithEqualityFn有解釋。
    Staat原始碼中的useBoundStoreWithEqualityFn有解釋。
    在這篇文章中,我們將了解Zustand原始碼中useBoundStoreWithEqualityFn函數是如何使用的。 上述程式碼摘自https://github.com/pmndrs/zustand/blob/main/src/traditional.ts#L80 useBoundStoreWi...
    程式設計 發佈於2024-11-03
  • 如何使用 Go 安全地連接 SQL 查詢中的字串?
    如何使用 Go 安全地連接 SQL 查詢中的字串?
    在Go 中的SQL 查詢中連接字串雖然文字SQL 查詢提供了一種簡單的資料庫查詢方法,但了解將字串文字與值連接的正確方法至關重要以避免語法錯誤和類型不匹配。 提供的查詢語法:query := `SELECT column_name FROM table_name WHERE colu...
    程式設計 發佈於2024-11-03
  • 如何在 Python 中以程式設計方式從 Windows 剪貼簿檢索文字?
    如何在 Python 中以程式設計方式從 Windows 剪貼簿檢索文字?
    以程式設計方式存取Windows 剪貼簿以在Python 中進行文字擷取Windows 剪貼簿充當資料的臨時存儲,從而實現跨應用程式的無縫數據共享。本文探討如何使用 Python 從 Windows 剪貼簿檢索文字資料。 使用 win32clipboard 模組要從 Python 存取剪貼簿,我們可...
    程式設計 發佈於2024-11-03
  • 使用 MySQL 預存程序時如何存取 PHP 中的 OUT 參數?
    使用 MySQL 預存程序時如何存取 PHP 中的 OUT 參數?
    使用MySQL 預存程序存取PHP 中的OUT 參數使用MySQL 儲存程序存取PHP 中的OUT 參數使用PHP 在MySQL 中處理預存程序時,取得由於文件有限,「 OUT”參數可能是一個挑戰。然而,這個過程可以透過利用 mysqli PHP API 來實現。 使用mysqli$mysqli =...
    程式設計 發佈於2024-11-03
  • 在 Kotlin 中處理 null + null:會發生什麼事?
    在 Kotlin 中處理 null + null:會發生什麼事?
    在 Kotlin 中處理 null null:會發生什麼事? 在 Kotlin 中進行開發時,您一定會遇到涉及 null 值的場景。 Kotlin 的 null 安全方法眾所周知,但是當您嘗試新增 null null 時會發生什麼?讓我們來探討一下這個看似簡單卻發人深省的情況吧! ...
    程式設計 發佈於2024-11-03

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3