About python objects and classes

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.

Class definition

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 ().

Constructor and destructor

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.

Class inheritance

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.

Parent method call by super

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.

Properties (getter / setter)

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.

Class variables

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

About python objects and classes
About Python variables and objects
[Python] About Executor and Future classes
Talking about old and new Python classes
[Introduction to Python3 Day 12] Chapter 6 Objects and Classes (6.3-6.15)
[Introduction to Python3 Day 11] Chapter 6 Objects and Classes (6.1-6.2)
About Python, len () and randint ()
About Python datetime and timezone
About Python and regular expressions
About Python and os operations
Python # About reference and copy
About Python sort () and reverse ()
About _ and __
About installing Pwntools and Python2 series
perl objects and python class part 2.
Python ABC-Abstract Classes and Duck Typing
Python: A Note About Classes 1 "Abstract"
About python dict and sorted functions
About dtypes in Python and Cython
Assignments and changes in Python objects
What was surprising about Python classes
About Python pickle (cPickle) and marshal
About Python, from and import, as
perl objects and python class part 1.
Python classes and instances, instance methods
About python slices
About python comprehension
About Python tqdm.
About python yield
Bind methods to Python classes and instances
About python, class
About python inheritance
About python, range ()
About python decorators
A story about Python pop and append
About python reference
About Python decorators
[Python] About multi-process
Talking about Python class attributes and metaclasses
How python classes and magic methods are working.
Organize the meaning of methods, classes and objects
Think about depth-priority and width-priority searches in Python
About the difference between "==" and "is" in python
[Python for Hikari] Chapter 09-02 Classes (Creating and instantiating classes)
A story about modifying Python and adding functions
[Python] Learn about asynchronous programming and event loops
[Python for Hikari] Chapter 09-01 Classes (Basics of Objects)
About the * (asterisk) argument of python (and itertools.starmap)
About shallow and deep copies of Python / Ruby
[python] Compress and decompress
About Class and Instance
About function arguments (python)
Batch design and python
Python iterators and generators
Python packages and modules
Vue-Cli and Python integration
[Python] Memo about functions
Python classes are slow
Ruby, Python and map
Summary about Python3 + OpenCV3
About cumprod and cummax