파이썬에서 정적 클래스 변수나 메서드를 가질 수 있나요? 이를 위해서는 어떤 구문이 필요한가요?
클래스 정의 내부에 선언되었지만 메서드 내부에 선언되지 않은 변수는 클래스 또는 정적 변수입니다:
>>> class MyClass:
... i = 3
...
>>> MyClass.i
3
밀러데브](https://stackoverflow.com/questions/68645/static-class-variables-in-python#answer-69067)가 지적했듯이, 이렇게 하면 클래스 수준의 i
변수가 생성되지만, 이는 인스턴스 수준의 i
변수와 구별되므로 다음과 같이 할 수 있습니다.
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
이것은 C++ 및 Java와는 다르지만 인스턴스에 대한 참조를 사용하여 정적 멤버에 액세스할 수 없는 C#과는 크게 다르지 않습니다.
클래스와 클래스 객체에 대한 내용은 파이썬 튜토리얼의 클래스 및 클래스 객체 관련 내용을 참조하세요.
스티브 존슨](#68656)이 정적 메서드에 관해 이미 답변했으며, 파이썬 라이브러리 참조의 [내장 함수]에도 문서화되어 있습니다.
class C:
@staticmethod
def f(arg1, arg2, ...): ...
beidy](#68747)는 메서드가 클래스 유형을 첫 번째 인수로 받기 때문에 staticmethod보다 classmethod를 권장하지만, 저는 이 접근 방식이 staticmethod에 비해 어떤 장점이 있는지 아직 잘 모르겠습니다. 여러분도 마찬가지라면 아마 상관없을 것입니다.
정적 클래스 정의가 아니라 내부에 선언된 변수는 @blair 콘래드 기도하였나니 δ1 메서드입니다 static", 클래스 또는 " 있다. 변수:
>>> class Test(object):
... i = 3
...
>>> Test.i
3
>>> t = Test()
>>> t.i # "static" variable accessed via instance
3
>>> t.i = 5 # but if we assign to the instance ...
>>> Test.i # we have not changed the "static" variable
3
>>> t.i # we have overwritten Test.i on t by creating a new attribute t.i
5
>>> Test.i = 6 # to change the "static" variable we do it by assigning to the class
>>> t.i
5
>>> Test.i
6
>>> u = Test()
>>> u.i
6 # changes to t do not affect new instances of Test
# Namespaces are one honking great idea -- let's do more of those!
>>> Test.__dict__
{'i': 6, ...}
>>> t.__dict__
{'i': 5}
>>> u.__dict__
{}
T.2 '의 인스턴스 변수' 를 어떻게 디이브이 좀있어 동기화되도록 " static"; 클래스 변수 '속성' 나 '를 직접 때 설정되었습니다 없습니다. 이 때문에 'i' 는 리바운드, 이는 'Test' 에서 '이름공간이 지기위해선 내의 다른 이름공간이. 스케쳐내 값을 변경할 수 있는 " static"; 가변으로 변경하십시오 합니다 (또는 객체) 범위 내에서 어디에 정의되었습니다. I put " static"; 파이썬 언약보다는 따옴표로 정적 변수를 가지고 있다는 점에서 C++, 자바 때문에 정말 못하며창조된.
또한, 정적 메서드는 @steve 존슨 역시 문서화했습니다 go-dell " 내장현 관한 답변됨 Functions". 의 파이썬 라이브러리 참조.
class Test(object):
@staticmethod
def f(arg1, arg2, ...):
...
또한 클라스메트로트 @beid 언급한 것과 비슷하게 스태틱메트로트. # 39 는 classmethod& 첫 인수는, s 클래스의. 예:
class Test(object):
i = 3 # class (or static) variable
@classmethod
def g(cls, arg):
# here we can use 'cls' instead of the class name (Test)
if arg > cls.i:
cls.i = arg # would be the same as Test.i = arg1
정적 및 클래스용 방법 # # 다른 방법을 모두 사용하여 쉽게 답을 얻을 수 있다고 할 때, 정적임 및 클래스용 내장현 데코레이터:
class Test(object):
# regular instance method:
def MyMethod(self):
pass
# class method:
@classmethod
def MyClassMethod(klass):
pass
# static method:
@staticmethod
def MyStaticMethod():
pass
일반적으로 ' ()' 가 첫 번째 인수를 미메트로트 바인딩되고 클래스 인스턴스 객체에는. 반면, 첫 번째 인수를 니클라스 토드 () '가' 클래스 객체 자체에 바인딩되지 (예를 들어, 이 경우 'Test'). 이때 인수를 위한 미스태틱메트로트 () ',' 바인딩되고 구매와 인수만 전혀 선택적입니다.
그러나, 구축, 정적 " variables". (뭐, 변경 가능 정적 변수가 아닌 경우, 아무튼 that& # 39 의 체계 내에서 약관보다.) tpc. 간단하지는 않다. 밀러데프 있다 있다고 지적한 바 그의 답변은 # 39, s 클래스, 속성, 진정한 문제는 Python& 않습니다를 " 정적임 variables". 고려해야 합니다.
class Test(object):
i = 3 # This is a class attribute
x = Test()
x.i = 12 # Attempt to change the value of the class attribute using x instance
assert x.i == Test.i # ERROR
assert Test.i == 3 # Test.i was not affected
assert x.i == 12 # x.i is a different object than Test.i
이 때문에 스자리 '선' '난' 의 'x' = 12 새로 추가되었습니다 인스턴스입니다 속성 값을 변경하는 대신 'Test' 클래스 'i' 속성.
class Test(object):
_i = 3
@property
def i(self):
return type(self)._i
@i.setter
def i(self,val):
type(self)._i = val
## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##
## (except with separate methods for getting and setting i) ##
class Test(object):
_i = 3
def get_i(self):
return type(self)._i
def set_i(self,val):
type(self)._i = val
i = property(get_i, set_i)
이제 할 수 있다.
x1 = Test()
x2 = Test()
x1.i = 50
assert x2.i == x1.i # no error
assert x2.i == 50 # the property is synced
이제 모든 정적 클래스 인스턴스 변수 간의 동기화 남아 있습니다. (참고: 즉, 클래스 정의 '을 보며 한 인스턴스입니다 자체 버전니다 _i'! 하지만 누군가 하고 이를 위해 그들은 그들이 # 39, t get, don& 자격이 있습니까???) 참고로, & # 39 는 기술적으로 'i' 는 아직 정적임 variable& # 39. 전혀. 이는 '속성', 이는 특수한 유형의 설명자. 그러나 이제 '속성' (mutable) 정적 클래스 전체에 대한 비헤이비어는 avamer synced 가변적입니다 인스턴스입니다.
정적 변수가 변경 불가 '속성' 는 단순히 생략하십시오 비헤이비어를 세터:
class Test(object):
_i = 3
@property
def i(self):
return type(self)._i
## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##
## (except with separate methods for getting i) ##
class Test(object):
_i = 3
def get_i(self):
return type(self)._i
i = property(get_i)
이제 'i' 속성 '한' 아트리부텔라로 반환되므로 시도중입니다 인스턴스입니다 설정합니다.
x = Test()
assert x.i == 3 # success
x.i = 12 # ERROR
참고로 위 - 해당 클래스의 메서드를 사용하여 인스턴스를 사용할 수 있습니다 사용할 때 그들은 없는 클래스 자체를 작동합니까 . 예를 들어:
x = Test()
assert x.i == Test.i # ERROR
# x.i and Test.i are two different objects:
type(Test.i) # class 'property'
type(x.i) # class 'int'
어설션 테스트리아 = 스자리 '선', 'i' 속성 때문에 오류가 발생합니다 'Test' 와 'x' 는 서로 다른 두 객체에는. 많은 사람들이 이 놀라운 발견하리니. 그러나 안 됩니다. 뒤로를 들어가면 우리의 'Test' 클래스 정의 및 검사 (두 번째 버전), 우리는 이 기록하십시오 라인:
i = property(get_i)
그러나 분명한 것은, 'i' 의 멤버 'Test' 반드시 '속성' 에서 '속성' 함수 객체 반환되었습니다 객체에는 유형입니다. 위의 찾을 수 있다면, 당신은 여전히 많다고 생각하고 관점에서 보면 대부분 다른 언어 (예를 들어, Java 나 c++). '속성' 객체에는 순서에 대한 연구를 검색하기를 합니다, 파이썬 속성, 메서드 해결안에서는 오더할 나님이시거늘 설명자를 프로토콜 및 기업소모성자재 (mro).
내가 제안하십시오 (파이썬 3) 아래 솔루션이므로 정보 제공용입니다. 나는 결코 그 좋은 solution" 보여줘야 ";). 나는 내 에뮬레이트할 수 있을지에 의구심을 따라 정적 변수가 다른 언어로 Python 는 아심과 비헤이비어를 실제로 필요하다. 그러나 실질적인 도움이 없이 모두인지 아래 도와야 할 만큼 더욱 파악하고 있다 "고 답했다. 업데이트: 이번 시도가 실제로 꽤 큰 , 이 같은 일을 준수하십시오 경우 (힌트: # 39 desktopplatforms don& t;; Python 은 매우 세련된 언어와 같은 다른 언어가 필요한 it 를 잘 안 나오는 신발 호르닝) 코드를 사용하여 이선 furman& # 39 의 오토메이티드 를 사용할 수 있습니다.
type(int) # class 'type'
type(str) # class 'type'
class Test(): pass
type(Test) # class 'type'
그러나 이 같은 메타클레스 정의할 수 있습니다.
class MyMeta(type): pass
이렇게 자신의 클래스 및 적용하십시오 (파이썬 3 만):
class MyClass(metaclass = MyMeta):
pass
type(MyClass) # class MyMeta
다음은 내가 hotenough. 메타클레스 디스크입니다. 시도_횟수 에뮬레이션하도록 " 정적임 variable"; 비헤이비어에 '로 끝난다. 기본적으로 이 작품 교체하십니까 기본값입니다 킬러 여부를 확인할 수 있는 속성 및 데이터 세터 버전으로 기술입니까 요청되었습니다 는 ", 정적 variable". 이 목록을 " 정적임 variables"; '스태틱바르메타스스태틱스' 속성에 저장됩니다. 처음에 사용하여 모든 속성 요청률 주문하십시오 대용품입니까 해결안에서는 해결해야 했다. 나는,,, 또는 '로 불리는 이 " 정적임 해결안에서는 order" " SRO". 이 작업은 요청되었습니다 속성의 집합을 보고 " 정적임 variables"; 주어진 클래스 (또는 부모 클래스). 이 경우, 클래스, 속성 표시되지 않습니다, SRO" " 거역한다면 퇴각하라 켜짐이 기본값입니다 속성용 get / set / 삭제 비헤이비어를 (즉, MRO" ";).
from functools import wraps
class StaticVarsMeta(type):
'''A metaclass for creating classes that emulate the "static variable" behavior
of other languages. I do not advise actually using this for anything!!!
Behavior is intended to be similar to classes that use __slots__. However, "normal"
attributes and __statics___ can coexist (unlike with __slots__).
Example usage:
class MyBaseClass(metaclass = StaticVarsMeta):
__statics__ = {'a','b','c'}
i = 0 # regular attribute
a = 1 # static var defined (optional)
class MyParentClass(MyBaseClass):
__statics__ = {'d','e','f'}
j = 2 # regular attribute
d, e, f = 3, 4, 5 # Static vars
a, b, c = 6, 7, 8 # Static vars (inherited from MyBaseClass, defined/re-defined here)
class MyChildClass(MyParentClass):
__statics__ = {'a','b','c'}
j = 2 # regular attribute (redefines j from MyParentClass)
d, e, f = 9, 10, 11 # Static vars (inherited from MyParentClass, redefined here)
a, b, c = 12, 13, 14 # Static vars (overriding previous definition in MyParentClass here)'''
statics = {}
def __new__(mcls, name, bases, namespace):
# Get the class object
cls = super().__new__(mcls, name, bases, namespace)
# Establish the "statics resolution order"
cls.__sro__ = tuple(c for c in cls.__mro__ if isinstance(c,mcls))
# Replace class getter, setter, and deleter for instance attributes
cls.__getattribute__ = StaticVarsMeta.__inst_getattribute__(cls, cls.__getattribute__)
cls.__setattr__ = StaticVarsMeta.__inst_setattr__(cls, cls.__setattr__)
cls.__delattr__ = StaticVarsMeta.__inst_delattr__(cls, cls.__delattr__)
# Store the list of static variables for the class object
# This list is permanent and cannot be changed, similar to __slots__
try:
mcls.statics[cls] = getattr(cls,'__statics__')
except AttributeError:
mcls.statics[cls] = namespace['__statics__'] = set() # No static vars provided
# Check and make sure the statics var names are strings
if any(not isinstance(static,str) for static in mcls.statics[cls]):
typ = dict(zip((not isinstance(static,str) for static in mcls.statics[cls]), map(type,mcls.statics[cls])))[True].__name__
raise TypeError('__statics__ items must be strings, not {0}'.format(typ))
# Move any previously existing, not overridden statics to the static var parent class(es)
if len(cls.__sro__) > 1:
for attr,value in namespace.items():
if attr not in StaticVarsMeta.statics[cls] and attr != ['__statics__']:
for c in cls.__sro__[1:]:
if attr in StaticVarsMeta.statics[c]:
setattr(c,attr,value)
delattr(cls,attr)
return cls
def __inst_getattribute__(self, orig_getattribute):
'''Replaces the class __getattribute__'''
@wraps(orig_getattribute)
def wrapper(self, attr):
if StaticVarsMeta.is_static(type(self),attr):
return StaticVarsMeta.__getstatic__(type(self),attr)
else:
return orig_getattribute(self, attr)
return wrapper
def __inst_setattr__(self, orig_setattribute):
'''Replaces the class __setattr__'''
@wraps(orig_setattribute)
def wrapper(self, attr, value):
if StaticVarsMeta.is_static(type(self),attr):
StaticVarsMeta.__setstatic__(type(self),attr, value)
else:
orig_setattribute(self, attr, value)
return wrapper
def __inst_delattr__(self, orig_delattribute):
'''Replaces the class __delattr__'''
@wraps(orig_delattribute)
def wrapper(self, attr):
if StaticVarsMeta.is_static(type(self),attr):
StaticVarsMeta.__delstatic__(type(self),attr)
else:
orig_delattribute(self, attr)
return wrapper
def __getstatic__(cls,attr):
'''Static variable getter'''
for c in cls.__sro__:
if attr in StaticVarsMeta.statics[c]:
try:
return getattr(c,attr)
except AttributeError:
pass
raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))
def __setstatic__(cls,attr,value):
'''Static variable setter'''
for c in cls.__sro__:
if attr in StaticVarsMeta.statics[c]:
setattr(c,attr,value)
break
def __delstatic__(cls,attr):
'''Static variable deleter'''
for c in cls.__sro__:
if attr in StaticVarsMeta.statics[c]:
try:
delattr(c,attr)
break
except AttributeError:
pass
raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))
def __delattr__(cls,attr):
'''Prevent __sro__ attribute from deletion'''
if attr == '__sro__':
raise AttributeError('readonly attribute')
super().__delattr__(attr)
def is_static(cls,attr):
'''Returns True if an attribute is a static variable of any class in the __sro__'''
if any(attr in StaticVarsMeta.statics[c] for c in cls.__sro__):
return True
return False
즉석에서 클래스뿐만 클래스 변수를 추가할 수도 있습니다
>>> class X:
... pass
...
>>> X.bar = 0
>>> x = X()
>>> x.bar
0
>>> x.foo
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: X instance has no attribute 'foo'
>>> X.foo = 1
>>> x.foo
1
클래스 인스턴스 변수 및 클래스용 변경할 수 있습니다.
class X:
l = []
def __init__(self):
self.l.append(1)
print X().l
print X().l
>python test.py
[1]
[1, 1]
개인적으로 저는 정적 메서드가 필요할 때마다 클래스 메서드를 사용하곤 합니다. 주로 클래스를 인자로 받기 때문입니다.
class myObj(object):
def myMethod(cls)
...
myMethod = classmethod(myMethod)
또는 데코레이터
class myObj(object):
@classmethod
def myMethod(cls)
정적 속성의 경우... 파이썬 정의를 찾아볼 시간입니다... 변수는 항상 변할 수 있습니다. 변수는 변경 가능한 것과 변경 불가능한 두 가지 유형이 있습니다. 또한 클래스 속성과 인스턴스 속성이 있습니다. 자바 및 C++의 의미에서 정적 속성과 같은 것은 없습니다.
피타고라스적 의미에서 정적 메서드를 사용하는 이유는 클래스와는 아무런 관계가 없는데! 저라면 클래스 메서드를 사용하거나 클래스와 독립적으로 메서드를 정의할 것입니다.
파이썬에서 정적 메서드는 classmethods라고 합니다. 다음 코드를 살펴보세요.
class MyClass:
def myInstanceMethod(self):
print 'output from an instance method'
@classmethod
def myStaticMethod(cls):
print 'output from a static method'
>>> MyClass.myInstanceMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method myInstanceMethod() must be called [...]
>>> MyClass.myStaticMethod()
output from a static method
내 인스턴스 메서드를 호출할 때 오류가 발생하는 것을 볼 수 있습니다. 이는 이 클래스의 인스턴스에서 해당 메서드를 호출해야 하기 때문입니다. 장식자]2 @classmethod_를 사용하여 myStaticMethod 메서드를 클래스 메서드로 설정합니다.
재미를 위해 다음과 같이 클래스의 인스턴스를 전달하여 클래스에서 _myInstanceMethod_를 호출할 수 있습니다:
>>> MyClass.myInstanceMethod(MyClass())
인스턴스 메서드에서 출력
한가지 특별한 일은 정적임 특성는 & 유의해야 합니다. 인스턴스 속성을, 아래 예의.
class my_cls:
my_prop = 0
#static property
print my_cls.my_prop #--> 0
#assign value to static property
my_cls.my_prop = 1
print my_cls.my_prop #--> 1
#access static property thru' instance
my_inst = my_cls()
print my_inst.my_prop #--> 1
#instance property is different from static property
#after being assigned a value
my_inst.my_prop = 2
print my_cls.my_prop #--> 1
print my_inst.my_prop #--> 2
즉, 우리가 속성 인스턴스 속성 값을 지정하기 전에 액세스하려는 thru& # 39. 정적 인스턴스로 값을 사용할 수 있습니다. 각 속성에 선언된 클래스의 정적 슬롯에 메모리를 항상 가지고 있다.
일부 멤버 변수를 정의할 때, 또는 비정적 멤버 중 하나가 될 수 있는 방법을 외부에서 방법에 따라 정적 변수를 가변입니다 밝혔다.
예를 들면 다음과 같습니다.
#!/usr/bin/python
class A:
var=1
def printvar(self):
print "self.var is %d" % self.var
print "A.var is %d" % A.var
a = A()
a.var = 2
a.printvar()
A.var = 3
a.printvar()
결과가
self.var is 2
A.var is 1
self.var is 2
A.var is 3
class A(object):
label="Amazing"
def __init__(self,d):
self.data=d
def say(self):
print("%s %s!"%(self.label,self.data))
class B(A):
label="Bold" # overrides A.label
A(5).say() # Amazing 5!
B(3).say() # Bold 3!
일반적으로, 모든 지정을 좁히어 aren& t # 39 이 만든 후. 단, 자체 레이블 '는' 에서 '는' 조회 수 있기 때문에 비록 정적 인스턴스로 가치 없는 어느 particular 연관된 여전히 따라 (class of the) 인스턴스입니다.
정적 클래스를 사용하여 메타클레스 적용 될 수도 있습니다.
class StaticClassError(Exception):
pass
class StaticClass:
__metaclass__ = abc.ABCMeta
def __new__(cls, *args, **kw):
raise StaticClassError("%s is a static class and cannot be initiated."
% cls)
class MyClass(StaticClass):
a = 1
b = 3
@staticmethod
def add(x, y):
return x+y
그 때마다 MyClass , # 39 초기화하지 시도하시겠습니까 우연히 you& 스태틱클레서로 ll 받을 수 있습니다.
정적 클래스 변수를 가질 수 있습니다 '' 가치가 아닐 수 있지만, 작업량의.
개념 증명 파이썬으로 here& # 39 의 경우 3 - 정확한 경위를 일치시키려면 뭐든지 할 수 있습니다 잘못된 코드 정적 변수가 단순한 면변형된 짓궂군요 의해 '':
class Static:
def __init__(self, value, doc=None):
self.deleted = False
self.value = value
self.__doc__ = doc
def __get__(self, inst, cls=None):
if self.deleted:
raise AttributeError('Attribute not set')
return self.value
def __set__(self, inst, value):
self.deleted = False
self.value = value
def __delete__(self, inst):
self.deleted = True
class StaticType(type):
def __delattr__(cls, name):
obj = cls.__dict__.get(name)
if isinstance(obj, Static):
obj.__delete__(name)
else:
super(StaticType, cls).__delattr__(name)
def __getattribute__(cls, *args):
obj = super(StaticType, cls).__getattribute__(*args)
if isinstance(obj, Static):
obj = obj.__get__(cls, cls.__class__)
return obj
def __setattr__(cls, name, val):
# check if object already exists
obj = cls.__dict__.get(name)
if isinstance(obj, Static):
obj.__set__(name, val)
else:
super(StaticType, cls).__setattr__(name, val)
또한 사용:
class MyStatic(metaclass=StaticType):
"""
Testing static vars
"""
a = Static(9)
b = Static(12)
c = 3
class YourStatic(MyStatic):
d = Static('woo hoo')
e = Static('doo wop')
그리고 일부 테스트:
ms1 = MyStatic()
ms2 = MyStatic()
ms3 = MyStatic()
assert ms1.a == ms2.a == ms3.a == MyStatic.a
assert ms1.b == ms2.b == ms3.b == MyStatic.b
assert ms1.c == ms2.c == ms3.c == MyStatic.c
ms1.a = 77
assert ms1.a == ms2.a == ms3.a == MyStatic.a
ms2.b = 99
assert ms1.b == ms2.b == ms3.b == MyStatic.b
MyStatic.a = 101
assert ms1.a == ms2.a == ms3.a == MyStatic.a
MyStatic.b = 139
assert ms1.b == ms2.b == ms3.b == MyStatic.b
del MyStatic.b
for inst in (ms1, ms2, ms3):
try:
getattr(inst, 'b')
except AttributeError:
pass
else:
print('AttributeError not raised on %r' % attr)
ms1.c = 13
ms2.c = 17
ms3.c = 19
assert ms1.c == 13
assert ms2.c == 17
assert ms3.c == 19
MyStatic.c = 43
assert ms1.c == 13
assert ms2.c == 17
assert ms3.c == 19
ys1 = YourStatic()
ys2 = YourStatic()
ys3 = YourStatic()
MyStatic.b = 'burgler'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
assert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b
assert ys1.d == ys2.d == ys3.d == YourStatic.d
assert ys1.e == ys2.e == ys3.e == YourStatic.e
ys1.a = 'blah'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
ys2.b = 'kelp'
assert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b
ys1.d = 'fee'
assert ys1.d == ys2.d == ys3.d == YourStatic.d
ys2.e = 'fie'
assert ys1.e == ys2.e == ys3.e == YourStatic.e
MyStatic.a = 'aargh'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
밀어버릴꺼에요 예.
class A:
counter =0
def callme (self):
A.counter +=1
def getcount (self):
return self.counter
>>> x=A()
>>> y=A()
>>> print(x.getcount())
>>> print(y.getcount())
>>> x.callme()
>>> print(x.getcount())
>>> print(y.getcount())
출력입니다
0
0
1
1
설명
here object (x) alone increment the counter variable
from 0 to 1 by not object y. But result it as "static counter"
이와 관련해 답변 , 정적 변수를 위한 설명자 상수입니다 사용할 수 있습니다. # 39 의 here& 예:
class ConstantAttribute(object):
'''You can initialize my value but not change it.'''
def __init__(self, value):
self.value = value
def __get__(self, obj, type=None):
return self.value
def __set__(self, obj, val):
pass
class Demo(object):
x = ConstantAttribute(10)
class SubDemo(Demo):
x = 10
demo = Demo()
subdemo = SubDemo()
# should not change
demo.x = 100
# should change
subdemo.x = 100
print "small demo", demo.x
print "small subdemo", subdemo.x
print "big demo", Demo.x
print "big subdemo", SubDemo.x
그 결과.
small demo 10
small subdemo 100
big demo 10
big subdemo 10
넌 언제나 설정 값을 올릴 경우 이를 무시한 채 조용히 예외가 아니다. ('패스' 위) your thing. # 39 you& 경우, C++, 자바 스타일을 찾는 사람들이 정적 클래스 변수:
class StaticAttribute(object):
def __init__(self, value):
self.value = value
def __get__(self, obj, type=None):
return self.value
def __set__(self, obj, val):
self.value = val
잠재적 혼동을 방지하기 위해 변수와 불변 객체를 정적임 대조합니다 하고 싶다.
마찬가지로, 정수, 일부 프리미티브 개체 유형, 그리고 Python 에서 유동합니다 문장열 투플스 변경할 수 있다. 즉,) 는 다음과 같은 뜻이 있는 객체에 의해 개체 유형 중 하나를 경우 앞서 언급했던 변경할 수 없습니다. 그러나 다른 개체, 객체 자체에 이름은 재할당되거나 변경할 수 없습니다.
정적임 가변적입니다 만드는 데 이를 한 단계 더 않는 것이 아니라, 모든 개체를 통해 변수 이름을 가리키십시오 라우팅할 현재는 점. (참고: 이는 일반적인 소프트웨어 개념 및 파이썬 적용되는 것은 아닙니다. # 39 others& 참조하십시오. 정역학 구축에 대한 자세한 내용은 게시물 의 파이썬).
예, 정적 변수와 메서드에 말해둘꼐요 쓸 수 있다.
>>> class A:
...my_var = "shagun"
>>> print(A.my_var)
shagun
>>> a = A()
>>> a.my_var = "pruthi"
>>> print(A.my_var,a.my_var)
shagun pruthi
그러나 정적 메서드는 항상 염두에 두고 있는 비정적 전화를 할 수 없는 방법으로 파이썬.
>>> class A:
... @staticmethod
... def my_static_method():
... print("Yippey!!")
...
>>> A.my_static_method()
Yippey!!
내가 찾은 가장 좋은 방법은 다른 클래스를 사용할 수 있습니다. 정보기술 (it) 을 사용할 수 있는 다른 객체에는 객체를 생성할 수 있습니다.
class staticFlag:
def __init__(self):
self.__success = False
def isSuccess(self):
return self.__success
def succeed(self):
self.__success = True
class tryIt:
def __init__(self, staticFlag):
self.isSuccess = staticFlag.isSuccess
self.succeed = staticFlag.succeed
tryArr = []
flag = staticFlag()
for i in range(10):
tryArr.append(tryIt(flag))
if i == 5:
tryArr[i].succeed()
print tryArr[i].isSuccess()
위의 예는 함께, I made a 클래스 이름이 '스태틱플라그'.
이 클래스의 정적 var '_success 제안하십시오 한다' (보면안돼 정적임 Var).
'클래스' 를 나타내는 트레이트 정규 수업을 위해 우리가 할 수 있습니다.
이젠 한 개체의 브라운아저씨의 플래깅 ('스태틱플라그'). 이 플래그는 모든 일반적인 객체에는 참조입니다 보낼 수 있다.
이러한 모든 객체에는 트리어 목록에 추가된 ''.
이 스크립트입니다 결과:
False
False
False
False
False
True
True
True
True
True
>>> def SomeFactory(some_var=None):
... class SomeClass(object):
... nonlocal some_var
... def print():
... print(some_var)
... return SomeClass
...
>>> SomeFactory(some_var="hello world").print()
hello world
사전, 정적 behavior" afaq " 목록이거나 사용할 수 있습니다. 사이에 인스턴스입니다.
class Fud:
class_vars = {'origin_open':False}
def __init__(self, origin = True):
self.origin = origin
self.opened = True
if origin:
self.class_vars['origin_open'] = True
def make_another_fud(self):
''' Generating another Fud() from the origin instance '''
return Fud(False)
def close(self):
self.opened = False
if self.origin:
self.class_vars['origin_open'] = False
fud1 = Fud()
fud2 = fud1.make_another_fud()
print (f"is this the original fud: {fud2.origin}")
print (f"is the original fud open: {fud2.class_vars['origin_open']}")
# is this the original fud: False
# is the original fud open: True
fud1.close()
print (f"is the original fud open: {fud2.class_vars['origin_open']}")
# is the original fud open: False