The other day I learned about 100 Days Of Code, which was popular on Twitter for a while. The purpose of this article is to keep a record and output how much I, as a beginner, can grow through 100 days of study. I think there are many mistakes and difficult to read. I would appreciate it if you could point out!
--Chapter 8 structure --Page 216 of this chapter
--Progress: Pages 87-91 --Chapter 4: Metaclasses and Attributes ――I will write down what I often forget or didn't know about what I learned today.
Defining get and set methods can lead to awkward code when doing calculations.
class OldResistor(object):
def __init__(self, ohms):
self._ohms = ohms
def get_ohms(self):
return self._ohms
def set_ohms(self, ohms):
self._ohms = ohms
r0 = OldResistor(100)
r0.set_ohms(r0.get_ohms() + 500)
print(r0.get_ohms())
# 600
Using plain attributes will result in cleaner code when calculating.
class Resistor(object):
def __init__(self, ohms):
self.ohms = ohms
self.voltage = 0
self.current = 0
r1 = Resistor(50e3)
r1.ohms = 400
r1.ohms += 200
print(r1.ohms)
# 600
Later, if you need special behavior when the attribute is set, you can add the @property decorator and its corresponding setter attribute. Also, in order for it to work properly, the names of both the ** setter method and the getter method must match the intended property name. ** **
class VoltageResistance(Resistor):
def __init__(self, ohms): #Initialize
super().__init__(ohms) #With ohms as an argument, of the parent class__init__Call
self._voltage = 0 #Instance variables_Declare voltage
@property # _Returns the value contained in voltage
def voltage(self):
return self._voltage
@voltage.setter #The setter method is executed every time a new value is assigned to voltage
def voltage(self, voltage): #Match property name
self._voltage = voltage
self.current = self._voltage / self.ohms
r2 = VoltageResistance(100)
print(r2.current)
# 0
r2.voltage = 10 # voltage.setter is called and passes 10 to voltage
print(r2.current)
# 0.1
In this way, you can extend the functionality while writing neat code by using plain attributes and using @property. When implementing setters and getters using the @property method, the following points should be suppressed so as not to reduce readability. Be careful not to cause the caller to behave unexpectedly, such as changing only the relevant object state, dynamically importing modules across objects, running slow helper hermitage, etc.! Also, if it is complicated or slow, it seems that it should be implemented using normal methods.
Recommended Posts