简体   繁体   中英

Calling another method to another class

i newbie on python programming, i so confused, why i cant call another method from another class,

this is my source- file : 8_turunan lanjut.py

class Karyawan(object):
'untuk kelas karyawan'
jml_karyawan = 0  # Class variable

# constructor
def __init__(self, kid, nama, jabatan):
    self.kid = kid
    self.nama = nama
    self.jabatan = jabatan
    Karyawan.jml_karyawan += 1


# method
def infoKaryawan(self):
    print "Karyawan baru masuk"
    print "==================="
    print "ID : %s " % self.kid
    print "Nama : %s " % self.nama
    print "Jabatan : %s " % self.jabatan

second source file : 9_turunan advance.py

    # cara mengakses/memakai class/membuat Object
class cobaa():
    obj = Karyawan("K001", "Ganjar", "Teknisi")
    obj.infoKaryawan()
    # tambah karyawan baru
    obj2 = Karyawan("K002", "Nadya", "Akunting")
    obj2.infoKaryawan()

    # tampilkan total Karyawan
print "-----------------------------"
print "Total Karyawan : %d " % Karyawan.jml_karyawan

how can i call method init and infoKaryawan to class cobaa on file 9_turunan advance.py

i already put from percobaan.Karyawan import __init__ on file : 9_turunan advance and its wrong, i dont know where's the problem of my source

here my directory sturcture directory structure

Your indentation is off in your class. It should read as follows:

class Karyawan(object):
    'untuk kelas karyawan'
    jml_karyawan = 0  # Class variable

    def __init__(self, kid, nama, jabatan):
        self.kid = kid
        self.nama = nama
        self.jabatan = jabatan
        Karyawan.jml_karyawan += 1

    def infoKaryawan(self):
        print "Karyawan baru masuk"
        print "==================="
        print "ID : %s " % self.kid
        print "Nama : %s " % self.nama
        print "Jabatan : %s " % self.jabatan

Then, in your other file, just import it as such: from filename import Karyawan

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM