Tags:
Forums: 

คือว่า ต้องการชื่อตัวแปร ของ ออปเจ็คของคลาสลูกอะค่ะ แต่เมื่อลองใช้คำสั่ง local () หรือ vars() มันแสดงชื่อของออปเจ็คในคลาสแม่ อย่างเดียวเลยค่ะ ตัวอย่าง code ที่ลองก็

คลาสแม่ค่ะ

class Model(object):

def __init__(self):

        print self.__class__.__name__    #  ปริ้นชื่อคลาส   ซึ่ง คลาสลูกก็ปริ้นชื่อได้ค่ะ

       #b = call.test_one()   
           print dir()   #  ลอง   
           print locals()  #  ลอง
           print vars()   #   ลอง

คลาสลูก

from Program import Model
from Obj import Obj
call = Obj()
class Student(Model,object):
b = call.test_one()
c = call.test_two()

a = Student()

คลาสที่ ลอง อิมพอร์ตเข้ามา

class Obj:
"Description of Class"
def test_one(self):
pass

def test_two(self):
    print "test_two"

เมื่อ extend คลาส model เข้ามาแล้ว มันไม่ปริ้น ชื่อ b และ c ในคลาสลูกให้ค่ะ แต่ถ้า เรียกฟังก์ชั่นแม่ มันก็ ปริ้น b ออกมานะคะ ไม่ทราบว่า ต้องการรู้ชื่อของobject ที่ คลาสลูก ต้องใช้คำสั่งอะไร ขอคำแนะนำด้วยค่ะ

Get latest news from Blognone
By: luckyman
ContributoriPhoneAndroidRed Hat
on 2 September 2009 - 03:00 #122371

แบบนี้รึเปล่าครับ

class Obj:
"Description of Class"
def test_one(self): pass
def test_two(self): print "test_two"

call = Obj()

class Model(object):
def init(self):
print self.class.name
b = call.test_one()
print locals()

class Student(Model, object):
b = call.test_one()
c = call.test_two()

ผลลัพธ์

a = Model()
Model
{'self': <main.Model object at 0x0000000002A39240>, 'b': None}

b = Student()
Student
{'self': <main.Student object at 0x0000000002A32E80>, 'b': None}

จัดฟอร์แมทโค้ดแบบนี้นะครับ

<code lang="python">
class Obj:
    "Description of Class"
    def test_one(self): pass
    def test_two(self): print "test_two"
</code>

By: punpungpan on 2 September 2009 - 10:25 #122399

ขอบคุณมากค่ะ ที่สอนจัด ฟอร์แมทให้ เพิ่งเข้ามาโพสต์เป็นครั้งแรกเลยค่ะ

ให้ Student เป็น คลาสลูกอะค่ะ แล้วต้องการตัวแปรของ

b = call.test_one()
c = call.test_two()

ต้องการให้มันแสดง b กับ c ใน คลาส Student อะค่ะ หรือว่า ถ้า ประกาศเป็น

b = call.test_one()
c = call.test_two()
w = call.test_two() # เพิ่มขึ้นมา

ก็มา print w เพิ่มมาด้วยอะค่ะ คือว่า หนูต้อการเอาชื่อของ object พวกนี้ ไปสร้างเป็นอย่างอื่นอีกทีอะค่ะ

ขอบคุณมากค่ะ

By: luckyman
ContributoriPhoneAndroidRed Hat
on 2 September 2009 - 23:45 #122490

ไม่ค่อยเข้าใจที่อธิบายนะครับ นี่เดาล้วนๆ

คิดว่าต้องการ bind method จาก Obj อื่นเข้ามาเป็น property ของ Model แล้วให้สืบทอดมาที่ Student ด้วย

class Obj:
"Description of Class"
def test_one(self): pass
def test_two(self): print "test_two"

call = Obj()

class Model:
b = call.test_one
c = call.test_two
def init(self):
print self.class.name

class Student(Model):
w = call.test_two

ผลรัน

a = Model()
Model
b = Student()
Student

dir(a)
['doc', 'init', 'module', 'b', 'c']

dir(b)
['doc', 'init', 'module', 'b', 'c', 'w']

a.c()
test_two

b.c()
test_two

b.w()
test_two

By: dafty
AndroidWindowsIn Love
on 3 September 2009 - 00:27 #122497


for ( String hello : hellos ) {
System.out.println(hello);
}

ลองดูๆ