Cara menggunakan python __init__ exception

Python telah menjadi bahasa berorientasi objek sejak bahasa Python sendiri dibuat. Untuk membuat dan menggunakan kelas dan objek pada Python benar-benar mudah. Pada tutorial ini Anda akan dibantu untuk menjadi ahli dalam penggunaan pemrograman berorientasi objek Python.

Jika Anda tidak memiliki pengalaman sebelumnya dengan pemrograman berorientasi objek (OOP), Anda mempelajarinya terlebih dahulu agar Anda dapat memahami konsep dasarnya.

Jika memang sudah mengerti konsep dasar OOP berikut ini adalah pengenalan dari Object-Oriented Programming (OOP) untuk membantu Anda.

Istilah Dalam OOP

IstilahPenjelasanClassPrototipe yang ditentukan pengguna untuk objek yang mendefinisikan seperangkat atribut yang menjadi ciri objek kelas apa pun. Atribut adalah data anggota (variabel kelas dan variabel contoh) dan metode, diakses melalui notasi titik.Class variableSebuah variabel yang dibagi oleh semua contoh kelas. Variabel kelas didefinisikan dalam kelas tapi di luar metode kelas manapun. Variabel kelas tidak digunakan sesering variabel contoh.Data memberVariabel kelas atau variabel contoh yang menyimpan data yang terkait dengan kelas dan objeknya.Function overloadingPenugasan lebih dari satu perilaku ke fungsi tertentu. Operasi yang dilakukan bervariasi menurut jenis objek atau argumen yang terlibat.Instance variableVariabel yang didefinisikan di dalam sebuah metode dan hanya dimiliki oleh instance kelas saat ini.InheritancePengalihan karakteristik kelas ke kelas lain yang berasal darinya.InstanceObjek individu dari kelas tertentu. Obyek obj yang termasuk dalam Lingkaran kelas, misalnya, adalah turunan dari Lingkaran kelas.InstantiationPenciptaan sebuah instance dari sebuah kelas.MethodJenis fungsi khusus yang didefinisikan dalam definisi kelas.ObjectContoh unik dari struktur data yang didefinisikan oleh kelasnya. Objek terdiri dari kedua anggota data (variabel kelas dan variabel contoh) dan metode.Operator overloadingPenugasan lebih dari satu fungsi ke operator tertentu.

Membuat Class Python

Statement class digunakan untuk membuat definisi kelas baru. Nama kelas segera mengikuti kelas kata kunci diikuti oleh titik dua sebagai berikut.

class ClassName: 'Optional class documentation string' class_suite

Dibawah ini adalah contoh cara membuat class dan penggunaanya :

class Employee:
'Common base class for all employees'
empCount = 0

def **init**(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

Membuat Instance Objects

Untuk membuat instances kelas, Anda memanggil class menggunakan nama class dan meneruskan argumen apa pun yang metode init terima.

This would create first object of Employee class
emp1 = Employee("Zara", 2000)
This would create second object of Employee class
emp2 = Employee("Manni", 5000)

Mengakses Atribut

Anda mengakses atribut objek menggunakan dot operator dengan objek. Variabel kelas akan diakses dengan menggunakan nama kelas sebagai berikut :

It is perfectly fine to raise an exception in __init__. You would then wrap the object initiation/creation call with try/except and react to the exception.

One potential odd result though is that __del__ is run anyway:

class Demo(object):
    def __init__(self, value):
        self.value=value
        if value==2:
            raise ValueError
    def __del__(self):
        print '__del__', self.value


d=Demo(1)     # successfully create an object here
d=22          # new int object labeled 'd'; old 'd' goes out of scope
              # '__del__ 1' is printed once a new name is put on old 'd'
              # since the object is deleted with no references 

Now try with the value

Demo(2)
Traceback (most recent call last):
  File "Untitled 3.py", line 11, in 
    Demo(2)           
  File "Untitled 3.py", line 5, in __init__
    raise ValueError
  ValueError
 __del__ 2 # But note that `__del__` is still run.
0 that we are testing for:

Demo(2)
Traceback (most recent call last):
  File "Untitled 3.py", line 11, in 
    Demo(2)           
  File "Untitled 3.py", line 5, in __init__
    raise ValueError
  ValueError
 __del__ 2 # But note that `__del__` is still run.

The creation of the object with value

Demo(2)
Traceback (most recent call last):
  File "Untitled 3.py", line 11, in 
    Demo(2)           
  File "Untitled 3.py", line 5, in __init__
    raise ValueError
  ValueError
 __del__ 2 # But note that `__del__` is still run.
0 raises a
Demo(2)
Traceback (most recent call last):
  File "Untitled 3.py", line 11, in 
    Demo(2)           
  File "Untitled 3.py", line 5, in __init__
    raise ValueError
  ValueError
 __del__ 2 # But note that `__del__` is still run.
2 exception and show that __del__ is still run to clean up the object.

Keep in mind that if you raise an exception during __init__ your object will not get a name. (It will, however, be created and destroyed. Since __del__ is paired with

Demo(2)
Traceback (most recent call last):
  File "Untitled 3.py", line 11, in 
    Demo(2)           
  File "Untitled 3.py", line 5, in __init__
    raise ValueError
  ValueError
 __del__ 2 # But note that `__del__` is still run.
6 it still gets called)

ie, just like this does not create

Demo(2)
Traceback (most recent call last):
  File "Untitled 3.py", line 11, in 
    Demo(2)           
  File "Untitled 3.py", line 5, in __init__
    raise ValueError
  ValueError
 __del__ 2 # But note that `__del__` is still run.
7:

>>> x=1/0
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: integer division or modulo by zero
>>> x
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'x' is not defined

Potential sneakier:

>>> x='Old X'
>>> x=1/0
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> x
'Old X'

Same thing if you catch an exception of __init__:

try:
    o=Demo(2)
except ValueError:
    print o          # name error -- 'o' never gets bound to the object...
                     # Worst still -- 'o' is its OLD value!

So don't try to refer to the incomplete object

Demo(2)
Traceback (most recent call last):
  File "Untitled 3.py", line 11, in 
    Demo(2)           
  File "Untitled 3.py", line 5, in __init__
    raise ValueError
  ValueError
 __del__ 2 # But note that `__del__` is still run.
9 -- it's gone out of scope by the time you get to
>>> x=1/0
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: integer division or modulo by zero
>>> x
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'x' is not defined
0. And the name
Demo(2)
Traceback (most recent call last):
  File "Untitled 3.py", line 11, in 
    Demo(2)           
  File "Untitled 3.py", line 5, in __init__
    raise ValueError
  ValueError
 __del__ 2 # But note that `__del__` is still run.
9 is either nothing (i.e.,
>>> x=1/0
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: integer division or modulo by zero
>>> x
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'x' is not defined
2 if you try to use it) or its old value.

So wrapping up (thanks to Steve Jessop for the idea), you can wrap the creation of the object and catch the exception. Just figure out how to react appropriately to the OS error you are looking at.

Apa itu exception pada Python?

Exception adalah objek Python yang mewakili kesalahan.

Apa itu init pada Python?

fungsi __init__.py memberikan label untuk suatu paket yang berupa sekumpulan file pada direktori sehingga mampu mencegah direktori dengan nama yang umum.

Di dalam statement try apa arti dari except?

except untuk menangani error yang mungkin kita sendiri tidak mengetahuinya. Biasanya try.. except ini digunakan untuk menangani error saat penggunaan IO, operasi database, atau pengaksesan indeks suatu list atau dictionary, dan berbagai kasus lainnya.

Apa yang dimaksud dengan modul pada Python?

Module pada Python adalah sebuah file yang berisikan sekumpulan kode fungsi, class dan variabel yang disimpan dalam satu file berekstensi .py dan dapat dieksekusi oleh interpreter Python.