Tôi đã hiểu cách thay thế các phương thức tại thời gian chạy bằng Python bằng cách xem các liên kết này. [Link1, Link2, & Link3].Phương pháp thay thế trong thời gian chạy không cập nhật Các thuộc tính riêng
Khi tôi thay thế phương thức "update_private_variable" của lớp A, nó sẽ được thay thế nhưng không cập nhật biến riêng tư.
import types
class A:
def __init__(self):
self.__private_variable = None
self.public_variable = None
def update_private_variable(self):
self.__private_variable = "Updated in A"
def update_public_variable(self):
self.public_variable = "Updated in A"
def get_private_variable(self):
return self.__private_variable
class B:
def __init__(self):
self.__private_variable = None
self.public_variable = None
def update_private_variable(self):
self.__private_variable = "Updated in B"
def update_public_variable(self):
self.public_variable = "Updated in B"
Khi gọi phương thức mà không cần thay thế:
a_instance = A()
a_instance.update_private_variable()
print(a_instance.get_private_variable())
#prints "Updated in A"
Khi gọi phương thức sau thay thế:
a_instance = A()
a_instance.update_private_variable = types.MethodType(B.update_private_variable, a_instance)
a_instance.update_private_variable()
print(a_instance.get_private_variable())
#prints None
Trong khi thay thế và gọi một phương thức mà cập nhật biến công cộng, hoạt động tốt
a_instance = A()
a_instance.update_public_variable = types.MethodType(B.update_public_variable, a_instance)
a_instance.update_public_variable()
print(a_instance.public_variable)
#prints 'Updated in B'
Có cách nào khác để thay thế phương thức của một thể hiện trong thời gian chạy, để các thuộc tính riêng được cập nhật bằng cách gọi phương thức thay thế?
Tôi gặp lỗi trên 'a_instance.update_private_variable()' sau khi rebinding 'update_private_variable'. 'TypeError: phương thức unbound update_private_variable() phải được gọi với đối tượng B làm đối số đầu tiên (có một cá thể A) thay vì' Cũng không có hệ thống công cộng/riêng tư thực tế nào. 'public_variable' và' __private_variable' đều có thể truy cập được với người dùng như nhau. – SuperBiasedMan
Bạn có thể gặp sự cố với tên "mangling" *, được gọi bởi tên thuộc tính '__leading_double_underscore' - sử dụng' _leading_single_underscore' để biểu thị riêng theo quy ước và dự trữ đôi để tránh xung đột giữa các lớp con. – jonrsharpe
@jonrsharpe: Tôi đã thử với '_leading_single_underscore', nó hoạt động bình thường. Nhưng theo yêu cầu của tôi, tôi không thể thay đổi _ "quy ước đặt tên" _ – user3262851