How to handle classes when creating your own MTV model I will leave it as a memo because I learned it.
The content is a rudimentary content during the elementary process. I will update what I have learned from time to time.
sample.py
class Person(object):
def eat(self):
print('eat')
person = Person()
person.eat()
Output result
eat
It is not necessary to have the object as an argument, but it is better to describe it as a remnant of the python2 system (as a code style).
You can call the class with person = Person ()
.
sample.py
class Person(object):
"""constructor"""
def __init__(self, food):
self.food = food
print('Food is ready')
def eat(self):
print('eat {}'.format(self.food))
"""Destructor"""
def __del__(self):
print('Thanks for the food')
person = Person('apple')
person.eat()
del person #Can also be written explicitly
Output result
Food is ready
eat apple
Thanks for the food
The constructor is the first thing that is called when creating an object.
Destructors, on the other hand, are called when an object runs out.
Since the __init__
method of the constructor is called at the very beginning, it is used when describing the initial settings.
There are other methods such as __new__
method.
self.food
can also be called from other methods.
sample.py
class Animal(object):
def eat(self):
print('eat')
class Monkey(Animal):
def eat(self, food):
self.food = food
print('eat {}'.format(self.food))
class Cheetah(Animal):
def run(self):
print('run')
animal = Animal()
animal.eat()
print('###########')
monkey = Monkey()
monkey.eat('banana') #Method override
print('###########')
cheetah = Cheetah()
cheetah.eat() #Class inheritance
cheetah.run() #Functional expansion
Output result
eat
###########
eat banana
###########
eat
run
If you pass the parent class as an argument of the child class, you can use the functions of the parent class. It can be used when you want to extend the function of the parent class only when there is a certain case. You can also overwrite the function with a child class.
sample.py
class Animal(object):
def __init__(self, food=None):
self.food = food
def eat(self):
print('eat')
class Monkey(Animal):
def __init__(self, food):
super().__init__(food)
def eat(self):
print('eat {}'.format(self.food))
animal = Animal()
animal.eat()
print('###########')
monkey = Monkey('banana')
monkey.eat()
Output result
eat
###########
eat banana
After the init function of the parent class is called by super ()
The init function of the child class is executed.
sample.py
class Animal(object):
def __init__(self, food=None, password=None):
self._food = food
self.password = password
"""getter"""
@property
def food(self):
return self._food
"""setter"""
@food.setter
def food(self, food):
if self.password == 'pass':
self._food = food
else:
# raise ValueError
print("error") #For confirmation
animal = Animal('banana', password='pass')
print(animal.food)
animal.food = "orange"
print(animal.food)
print("##############")
animal2 = Animal('banana')
print(animal2.food)
animal2.food = "orange"
print(animal2.food)
Output result
banana
orange
##############
banana
error
By using properties, you can read variables that you do not want to be overwritten from the outside.
It is said that it can be explicitly expressed when you do not want the value to be rewritten.
It is possible to prevent a situation in which a third party performs an operation not intended by the designer and an error occurs.
_Variable name
By adding an underscore
It is said that it makes sense to hide it from the outside.
You can refer to variables directly because they have little effect on the actual operation.
The getter adds @property
and makes the function name the target variable name.
The setter can be set with .setter
to the function name for which the property is set.
It is said that it is used when it is acceptable to overwrite only under certain conditions.
__ Variable name
There is also a method of adding two underscores, but in the parent class and the child class
When the method name is duplicated, it is generally used for the purpose of avoiding conflicts.
Please see here for details.
sample.py
class Person(object):
eated_list = [] #Class variables
def eat(self, food):
print('eat {}'.format(food))
self.eated_list.append(food)
personA = Person()
personA.eat("apple")
print(personA.eated_list)
personB = Person()
personB.eat("orange")
print(personB.eated_list)
Output result
eat apple
['apple']
eat orange
['apple', 'orange']
A class variable is a variable that can be shared by all generated objects.
Therefore, there is a risk that information that you do not want to share between objects will be shared like the above code.
To avoid this, bring the variable inside the __init__
method and
Every time an object is created, it is necessary to describe the variable initialization process.
Recommended Posts