Python basic grammar note (3)

at first

I'm studying Python. I made it as a memo, so there may be some typographical errors.

Objects and classes

A class is a blueprint, and an instance is a materialization of that blueprint.

Object-oriented is a way of thinking that captures the behavior of a system as an interaction between objects.

With object orientation, classes and instances were conceived.

Class definition

class Person(object):
    def say_something(self):
        print('hello')

# Call a class to create an object
person = Person()
person.say_something()

>>>hello

Class initialization and class variables


class Person(object):
 #Initialization and initialization image
    def __init__(self):
        print('First')

    def say_something(self):
        print('hello')

person = Person()

>>>First

# You can't let yourself hold a value without self
class Person(object):
    def __init__(self, name):
        self.name = name
        print(self.name)

    def say_something(self):
        print('hello')

person = Person('Mike')
>>>Mike

# Call in a function
class Person(object):
    def __init__(self, name):
        self.name = name
        print(self.name)

    def say_something(self):
        print('I am {}. hello'.format(self.name))

person = Person('Mike')
person.say_something()

>>>Mike
>>>I am Mike. hello

Constructor and destructor

The first object that is initialized and called is the constructor Last called object


class Person(object):
    def __init__(self, name):
        self.name = name
        print(self.name)

    def say_something(self):
        print('I am {}. hello'.format(self.name))

    def __del__(self):
        print('good bye')

person = Person('Mike')
person.say_something()

>>>Mike
>>>I am Mike. hello
>>>good bye

Class inheritance

Inherit and write code neatly

class Car(object):
    def run(self):
        print('run')
# pass means do nothing
class ToyotaCar(Car):
    pass

class TeslaCar(Car):
    def auto_run(self):
        print('auto_run')
car = Car()
car.run()

toyota_car = ToyotaCar()
toyota_car.run()
print('##################')
tesla_car = TeslaCar()
# Since it inherits the Car class, it can be executed.
tesla_car.run()
tesla_car.auto_run()

>>>run
>>>run
>>>##################
>>>run
>>>auto_run

Overriding class inheritance methods and calling parent methods with super


class Car(object):
    def __init__(self, model=None):
        self.model = model

    def run(self):
        print('run')

class ToyotaCar(Car):
    print('fast')

class TeslaCar(Car):
    def __init__(self, model='Model S', enable_auto_run=False):

        super().__init__(model)
        self.enable_auto_run = enable_auto_run

    def run(self):
        print('super fast')

    def auto_run(self):
        print('auto_run')

car = Car()
car.run()

toyota_car = ToyotaCar('Lexus')
toyota_car.run()
print('##################')
tesla_car = TeslaCar('Model S')
tesla_car.run()
tesla_car.auto_run()

>>>fast
>>>run
>>>run
>>>##################
>>>super fast
>>>auto_run

Setting attributes using properties

When using properties, when it is okay to rewrite under certain conditions

class Car(object):
    def __init__(self, model=None):
        self.model = model

    def run(self):
        print('run')

class ToyotaCar(Car):
    print('fast')

class TeslaCar(Car):
    def __init__(self, model='Model S', enable_auto_run=False):

        super().__init__(model)
        self._enable_auto_run = enable_auto_run
# Description that cannot be rewritten
    @property
    def enable_auto_run(self):
        return self._enable_auto_run 

    def run(self):
        print('super fast')

    def auto_run(self):
        print('auto_run')


teslaCar = TeslaCar('Model S')
print(tesla_Car.enable_auto_run)

>>>False

# k Description when rewriting is acceptable
class Car(object):
    def __init__(self, model=None):
        self.model = model

    def run(self):
        print('run')

class ToyotaCar(Car):
    print('fast')

class TeslaCar(Car):
    def __init__(self, model='Model S', enable_auto_run=False):

        super().__init__(model)
        self._enable_auto_run = enable_auto_run

    @property
    def enable_auto_run(self):
        return self._enable_auto_run 

    @enable_auto_run.setter
    def enable_auto_run(self, is_enable):
        self._enable_auto_run = is_enable

    def run(self):
        print('super fast')
    def auto_run(self):
        print('auto_run')


tesla_Car = TeslaCar('Model S')
# Put True first
tesla_Car.enable_auto_run = True
print(TeslaCar.enable_auto_run)

>>>True

Precautions when treating a class as a structure

・ If you generate a class and enter a value later, it will lead to a bug if you do not check the contents of the class.

Duck typing


class Person(object):
    def __init__(self, age=1):
        self.age = age

    def drive(self):
        if self.age >= 18:
            print('ok')
        else:
            raise Exception('No drive')

class Baby(Person):
    def __init__(self, age=1):
        if age < 18:
            super().__init__(age)
        else:
            raise ValueError

class Adult(Person):
    def __init__(self, age=18):
        if age >= 18:
            super().__init__(age)
        else:
            raise ValueError

baby = Baby()
adult = Adult()

class Car(object):
    def __init__(self, model=None):
        self.model = model
    def run(self):
        print('run')
    def ride(self, person):
        person.drive()

car = Car()
car.ride(adult)

>>>ok

Abstract class

import abc

class Person(metaclass=abc.ABCMeta): 
    def __init__(self, age=1):
        self.age = age

    @abc.abstractclassmethod
    def drive(self):
        pass


class Baby(Person):
    def __init__(self, age=1):
        if age < 18:
            super().__init__(age)
        else:
            raise ValueError
    def drive(self):
        raise Exception('No drive')

class Adult(Person):
    def __init__(self, age=18):
        if age >= 18:
            super().__init__(age)
        else:
            raise ValueError

    def drive(self):
        print('ok')


baby = Baby()
adult = Adult()

>>>ok

Multiple inheritance

class Person(object):
    def talk(self):
        print('talk')
    def run(self):
        print('parson run')


class Car(object):
    def run(self):
        print('car run')
# The argument put on the left side executes first
class PersonCarRobot(Car, Person):
    def fly(self):
        print('fly')

parson_car_robot = PersonCarRobot()
parson_car_robot.talk()
parson_car_robot.run()
parson_car_robot.fly()

>>>talk
>>>car run
>>>fly

Class variables

Shared by all objects

class Person(object):

    kind = 'human'

    def __init__(self, name):
        self.name = name

    def who_are_you(self):
        print(self.name, self.kind)

a = Person('A')
a.who_are_you()
b = Person('B')
b.who_are_you()

>>>A human
>>>B human

Class methods and static methods

You can call class methods even if they are not objects


class Person(object):

    kind = 'human'

    def __init__(self):
        self.x = 100

    @classmethod
    def what_is_your_kind(cls):
        return cls.kind

    @staticmethod
    def about(year):
        print('about human {}'.format(year))

a = Person()
print(a.what_is_your_kind())

b = Person()
print(b.what_is_your_kind())

Person.about(1998)

>>>human
>>>human
>>>about human 1998

Special method

class Word(object):

    def __init__(self, text):
        self.text = text

    def __str__(self):
        return 'Word!!!!!!!!!!!'

    def __len__(self):
        return len(self.text)

    def __add__(self, word):
        return self.text.lower() + word.text.lower()

    def __eq__(self, word):
        return self.text.lower() == word.text.lower()

w = Word('text')
w2 = Word('text')

print(w == w2)

Recommended Posts

Python basic grammar note (4)
Python basic grammar note (3)
Python3 basic grammar
Python basic grammar / algorithm
Python basic grammar (miscellaneous)
Python basic grammar memo
Python installation and basic grammar
Python Basic Grammar Memo (Part 1)
Python basic grammar (miscellaneous) Memo (2)
Python note
I learned Python basic grammar
Python basic grammar (miscellaneous) Memo (4)
Python (Python 3.7.7) installation and basic grammar
Java and Python basic grammar comparison
Basic grammar of Python3 system (dictionary)
Python study note_002
Python programming note
RF Python Basic_01
[Python] Learning Note 1
Python study note_004
Basic Python writing
Python grammar notes
[Note] openCV + python
RF Python Basic_02
Python beginner's note
[Basic grammar] Differences between Ruby / Python / PHP
[Python] I personally summarized the basic grammar.
Basic grammar of Python3 system (character string)
Basic grammar of Python3 system (included notation)
[Go] Basic grammar ① Definition
Python I'm also basic
Python Basic Course (7 Dictionary)
[Note] future sentence ~ Python ~
[Note] File reading ~ Python ~
Basic sorting in Python
[Go] Basic grammar ② Statement
Python ~ Grammar speed learning ~
Python basic course (9 iterations)
[python] class basic methods
Python Basic Course (11 exceptions)
Python basic course (6 sets)
Python3 cheat sheet (basic)
Python Basic Course (Introduction)
Python basic memorandum part 2
[Go] Basic grammar ③ Pointer
Python basic memo --Part 2
VBA user tried using Python / R: basic grammar
Note to daemonize python
Note: python Skeleton Nya
Basic Python command memo
Basic knowledge of Python
(Note) Basic statistics on Python & Pandas on IBM DSX
Python Tkinter Primer Note
OpenCV basic code (python)
Python basic memo --Part 1
python memorandum super basic
Python basic course (8 branches)
Python basic if statement
Python Basic Course (3 Python Execution)
Python Basic --Pandas, Numpy-
[For beginners] Learn basic Python grammar for free in 5 hours!