2010-07-13 29 views
34

Tôi quan tâm đến việc phân lớp kiểu được xây dựng trong int bằng Python (Tôi đang sử dụng câu 2.5), nhưng gặp một số vấn đề khi khởi tạo làm việc.Phân lớp int trong Python

Dưới đây là một số mã ví dụ, điều này khá rõ ràng.

class TestClass(int): 
    def __init__(self): 
     int.__init__(self, 5) 

Tuy nhiên, khi tôi cố gắng sử dụng này, tôi nhận được:

>>> a = TestClass() 
>>> a 
0 

nơi tôi mong đợi kết quả được 5.

Tôi đang làm gì sai? Google, cho đến nay, vẫn chưa được rất hữu ích, nhưng tôi không thực sự chắc chắn những gì tôi nên tìm kiếm

+2

câu hỏi StackOverflow này đề cập đến cùng một chủ đề chi tiết hơn: http: //stackoverflow.com/questions/33534/extending-base-classes-in-python – sunetos

+0

Ngoài ra, tại đây: http://stackoverflow.com/questions/399022/why-cant-i-subclass-datetime-date – Arkady

Trả lời

54

int là không thay đổi nên bạn không thể sửa đổi nó sau khi nó được tạo ra, sử dụng __new__ thay

class TestClass(int): 
    def __new__(cls, *args, **kwargs): 
     return super(TestClass, cls).__new__(cls, 5) 

print TestClass() 
3

Mặc dù các câu trả lời hiện tại chính xác có khả năng chưa hoàn thành.

ví dụ:

a = TestClass() 
b = a - 5 
print type(b) 

Sẽ hiển thị b làm số nguyên, nơi bạn có thể muốn nó là một TestClass.

Dưới đây là một câu trả lời cải thiện

class positive(int): 
    def __new__(cls, value, *args, **kwargs): 
     if value < 0: 
      raise ValueError, "positive types must not be less than zero" 
     return super(positive, cls).__new__(cls, value) 

    def __add__(self, other): 
     res = super(positive, self).__add__(other) 
     return self.__class__(max(res, 0)) 

    def __sub__(self, other): 
     res = super(positive, self).__sub__(other) 
     return self.__class__(max(res, 0)) 

    def __mul__(self, other): 
     res = super(positive, self).__mul__(other) 
     return self.__class__(max(res, 0)) 

    def __div__(self, other): 
     res = super(positive, self).__div__(other) 
     return self.__class__(max(res, 0)) 

Bây giờ cùng một loại thử nghiệm

a = positive(10) 
b = a - 9 
print type(b) 

sẽ in 'tích cực'

Các vấn đề liên quan