![](/img/trans.png)
[英]How To define arguments in ironpython for the Microsoft.SqlServer.SMO.Scripter.Script Class
[英]how to define IronPython static property?
我發現之前討論過在 (Iron)Python 中定義 Static 方法,但是,我沒有找到任何關於 Static 屬性的信息。 I assume you can definitively create Static Properties since properties are just methods for the .NET CLR and that's what I did in the code below, however, it looks like by calling the Static Property "StaticField" I cannot access the value of the Static Field " __staticField" 它被鏈接到而不是我得到一個存儲屬性的引用? ,但是如果我使用用作獲取屬性的 Static 方法“getStaticField” ,它確實正確地給了我值“2”。
所以問題是:你能在 (Iron)Python 中定義 Static 屬性嗎? 以及如何使用它們來獲取值而不是對屬性方法的引用?
提前致謝。
class Test(object):
__instanceField = 0
__staticField = 0
# Instance Property (read-only)
def getInstanceField(self):
return self.__instanceField
InstanceField = property(getInstanceField, None, None)
# Static Property (read-only)
@staticmethod
def getStaticField():
return Test.__staticField
StaticField = property(getStaticField, None, None)
# Instance Method
def instanceMethod(self, n):
self.__instanceField += 1
print 'instanceMethod', n
# Static Method
@staticmethod
def staticMethod(n):
Test.__staticField += 1
print 'staticMethod', n
# Calling Static Methods
Test.staticMethod(5)
Test.staticMethod(10)
# Calling Instance Methods
t = Test()
t.instanceMethod(5)
t.instanceMethod(10)
print 'InstanceProperty', t.InstanceField
#prints 2
print 'StaticProperty', Test.StaticField
#prints: <property object at 0x000000000000002B>
print 'StaticPropertyMethod', Test.getStaticField()
#prints 2
這個答案通常適用於 python,而不是特定於 IronPython。
property
可以方便地創建一個描述符,一個 object,它提供一個__get__
和可選的__set__
和__del__
方法。 __get__
方法接受目標實例的 arguments 以及關聯的 class,但永遠不會為類調用__set__
。 如果您需要的只是 getter 行為而沒有 setter 行為,則只需直接實現一個描述符
class StaticGetter(object):
def __init__(self, attr):
self.attr = attr
def __get__(self, instance, owner):
# owner is the class, your getter code here
return getattr(owner, attr)
class Test(object):
__staticField = 0
staticField = StaticGetter('_Test__staticField')
在設置器的情況下,您可以提供一個__set__
方法,該方法從實例推斷 class,但安排Test.staticField = newvalue
改為調用Test.staticField.someSetterMethod(newvalue)
將需要一個新的元類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.