簡體   English   中英

python中尋址屬性的樣式

[英]Style of addressing attributes in python

這個問題是風格之一。 由於python中的屬性不是私有的,使用類似my_obj.attr之類的東西直接在類之外解決它們是否常見? 或者,也許,通過像get_attr()這樣的成員函數來實現它更好嗎?

聽起來你想要使用屬性:

class Foo(object):
    def __init__(self, m):
        self._m = m
    @property
    def m(self):
        print 'accessed attribute'
        return self._m
    @m.setter
    def m(self, m):
        print 'setting attribute'
        self._m = m


>>> f = Foo(m=5)
>>> f.m = 6
setting attribute
>>> f.m
accessed attribute
6

這是訪問變量的最自適應方式,對於您不需要執行此操作的簡單用例,在Python中,您可以隨時更改設計以便以后免費使用屬性。

首先創建類的實例:

myinstance = MyClass()
myinstance.attr

否則你會收到類似AttributeError: class MyClass has no attribute 'attr'的錯誤AttributeError: class MyClass has no attribute 'attr'在嘗試執行MyClass.attr時, AttributeError: class MyClass has no attribute 'attr'

是的,這是一種常見的做法。 如果您想要更好地控制檢索屬性的方式,請考慮使用__getattribute__和/或__getattr__

暫無
暫無

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

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