簡體   English   中英

有沒有辦法在不添加“foo =”的情況下更改類變量?

[英]Is there a way to change a class variable without adding 'foo = '?

我有一個類,並且想更改它的一個對象(類似於列表的 pop 方法),而不添加foo = foo.bar()

簡單來說,我想做foo.bar()而不是foo = foo.bar() 這在python中可能嗎? 這是我擁有的一些代碼,希望能進一步理解:

class mystr(str):
    def pop(self, num):
        self = list(self)
        changed = self.pop(num)  # The particular character that was removed
        self = ''.join(self)  # The rest of the string
    
        # Somewhere in here i need to be able to change the actual variable that pop() was called on

        return changed  # Emulates python lists' way of returning the removed element.


my_var = mystr("Hello World!")
print(my_var.pop(4)  # Prints 'o', as you would expect
print(my_var)  # But this still prints 'Hello World!', instead of 'Hell World!'
# It isn't modified, which is what i want it to do

您可以,但不能使用str


您正在尋找的是一種改變對象的方法。 對於您自己編寫的大多數類,這樣做很簡單:

class Foo:
    def __init__(self):
        self.stuff = 0
    def example(self):
        self.stuff += 1

在這里,在Foo實例上調用example通過改變它的stuff實例屬性來改變它。


然而, str是不可變的。 它將其數據存儲在 C 級數據結構中,並且不提供修改器方法,因此無法修改其數據。 即使您使用ctypes繞過保護,您也會遇到一堆內存損壞錯誤。

您可以在子類中添加自己的屬性,這些屬性是可變的,但是如果您這樣做是為了偽造可變字符串,那么您最好不要從str繼承。 在這種情況下從str繼承只會導致錯誤,一些代碼查看您的“假”數據,而其他代碼查看“真實”底層str數據。


很可能,要走的路將是兩種選擇之一。 第一種是只使用常規字符串,而不使用子類或要添加的方法。 第二種是編寫一個不繼承自str

您可以通過封裝一個字符串來實現這一點,而不是從它繼承

class mystr:
    def __init__(self, string):
        self._str = string

    def pop(self, num):
        string_list = list(self._str)
        changed = string_list.pop(num)  # The particular character that was removed
        self._str = ''.join(string_list)  # The rest of the string

        return changed  # Emulates python lists' way of returning the removed element.

    def __repr__(self):
        return self._str

使用此類運行相同的代碼將打印:

o
Hell World!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM