In [2]:
class Test:
def __init__(self):
self.public_field = 5
self.__private_field = 6
self._protected_field = 7
def __private_method(self):
pass
if __name__ == '__main__':
t = Test()
t.public_field = 10
t.__private_field = 11
t._protected_field = 12
In [3]:
t.public_field
Out[3]:
In [4]:
t.__private_field
Out[4]:
In [5]:
t._protected_field
Out[5]:
In [7]:
class Test:
def __init__(self):
self.color = "red"
def set_color(self,clr):
self.color = clr
def get_color(self):
return self.color
In [8]:
t = Test()
t.set_color("blue")
print(t.get_color())
In [9]:
t1 = Test()
In [10]:
print(t1.get_color())
In [11]:
t1.color
Out[11]:
In [12]:
class Test:
def __init__(self):
self.__color = "red"
@property
def color(self):
return self.__color
@color.setter
def color(self,clr):
self.__color = clr
# get 역할을 하는 어노테이션은 @property 이고, set역할을 하는 어노테이션은 @color.setter
In [13]:
t = Test()
t.color = "blue"
print(t.color)
In [14]:
class Celsius:
def __init__(self):
pass
def to_fahrenheit(self):
return (self._temperature * 1.8) + 32
@property
def temperature(self):
print("Getting value")
return self._temperature
@temperature.setter
def temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
In [20]:
c = Celsius()
c._temperature = -300
print(c.temperature)
In [34]:
class Test1:
def __init__(self):
pass
@property
def property1(self):
print("a")
return self._property
@property1.setter
def property(self, value):
if value >= 5:
print("over 5")
else:
print("down 5")
self._property1 = value
In [38]:
k = Test1()
k._property = 1
In [39]:
k.property
Out[39]:
In [ ]: