Getting Started with Python for PHPer-Classes

This is a continuation from Functions. This time I will explain about the class!

Class definition

First, let's compare the basic description methods. It's not so different from Gatsuri, so I think you can read it easily. However, there are quite a few differences. ..

PHP code

<?php

class Hoge {
    static private $defaultValue = 'hogehoge';
    private $value = null;

    public function __construct($value=null) {
        if ($value) {
            $this->value = $value;  
        } else {
            $this->value = self::$defaultValue;
        }
    }

    public function getValue() {
        return $this->value;
    }
}

$hoge = new Hoge();
echo $hoge->getValue();

Python code

# coding=utf8

class Hoge(object):
    default_value = 'hogehoge'

    def __init__(self, value=None):
        if value:
            self.value = value
        else:
            self.value = self.default_value

    def get_value(self):
        return self.value

hoge = Hoge()
print(hoge.get_value())

How to write

Class definition is done using class as in PHP. Like the ʻif statementandfunction, the scope is represented by indentinstead of{}. Again, don't forget the : (colon)` at the end of the class definition.

Inherit the object class!

When creating a plain class, be sure to inherit ʻobject class`. You can make it without inheriting it, but there are many advantages to inheriting it. If you want to know more, please refer to here.

Python classes have no access modifiers!

It's one of the places where you can easily tell the difference by comparing the sources. There is no access modifier such as public in Python, and basically everything is treated as public. For the time being, if you add __ before the name of the instance variable or method, you will not be able to access it.

constructor

Needless to say, the constructor method name is different. PHP is __construct, and Python is __init __.

What is the method argument self? ..

** It is one of the parts called "Python Kimoi !!!" **. .. This self is a reference to itself (your instance). It's too complicated to explain why such a thing is done, so please google each one. ..

The important thing here is that ** the first argument of the method always passes a reference to itself **.

Be careful with the definitions of instance variables and class variables!

In the case of PHP, the definition is separated by using the static modifier, but in the case of Python, the definition of the instance variable must be done in themethod such asinit. All variables defined outside the method are class variables. If you execute the sample below, Hoge.hoge will be output, but you can see that Hoge.piyo` causes an error.

# coding=utf8

class Hoge(object):
    hoge = 'hoge'  #Class variables

    def __init__(self):
        self.piyo = 'piyo'  #Instance variables

print(Hoge.hoge)

#You cannot access the instance variable because it is not instantiated.
print(Hoge.piyo)

Please note that it is easy to overlook (forget). ..

Reference to instance variable / method

This is also self-explanatory, but in PHP it is $ this-> value and in Python it is self.value. There is also a difference between the arrow operator and the dot operator, so be careful.

Regarding class variables and static methods, in PHP it is written as sefl :: $ hoge, but Python can be accessed with self.hoge like instance variables.

Class inheritance

Let's talk about class inheritance. As always, start with the sample code.

PHP code

<?php

class BaseClass {
    public function __construct($value) {
        $this->value = $value;
    }

    public function getValue() {
        return$this->value;
    }
}

class SubClass extends BaseClass {
    public function __construct($value) {
        $value = $value * 2;
        parent::__construct($value);
    }
}

$hoge = new SubClass(10);
echo $hoge->getValue();

Python code

# coding=utf8

class BaseClass(object):
    def __init__(self, value):
        self.value = value

    def get_value(self):
        return self.value

class SubClass(BaseClass):
    def __init__(self, value):
        value = value * 2
        super(SubClass, self).__init__(value)

hoge = SubClass(10)
print(hoge.get_value())

Description of inheritance

I've already done it in the explanation of the class definition, but I will explain it again. To inherit a class in Python, just write the name of the class you want to inherit in () after the class name.

class SubClass(BaseClass):

Call a method of the parent class

In Python, use the super function to access the parent class. In the sample, the method (constructor) of the parent class is called in the constructor, but you can call it in the same way with a normal method.

super(SubClass, self).__init__(value)

When disassembled, it looks like the following.

super(Own class,Own instance).Function you want to call(argument)

Multiple inheritance of classes

How Python supports multiple inheritance of classes! It's a convenient multiple inheritance, but it tends to be complicated, so use it with caution.

How to describe multiple inheritance

Same as normal inheritance description. The class you want to inherit is described in (), but if there are multiple classes, just separate them with , (comma).

class SubClass(HogeClass, PiyoClass):

The order in which the constructors are called

** Be careful as it is confusing here! ** ** First, sample code.

# coding=utf8

class A(object):
    def __init__(self):
        super(A, self).__init__()
        print('A')

class B(object):
    def __init__(self):
        super(B, self).__init__()
        print('B')

class C(A, B):
    def __init__(self):
        super(C, self).__init__()
        print('C')

instance = C()

There is a C class that inherits two things, the ʻA classand theB class`. If you do this, you will get the following result.

B
A
C

If you look at the result, you can see that they are called in the order of B-> A-> C.

Why is the super function written in the parent class?

I explained earlier that the super function is for accessing the parent class, but strictly speaking, it is for accessing the parent or sibling class. The super function is needed because the parent classes of the C class, the ʻA class and the B class`, have a sibling relationship.

Maybe this explanation isn't quite right yet, so take a look at the next one!

Why is the order B-> A-> C?

The definition of C class isclass C (A, B):, and ʻA classis declared first. In this case, the immediate parent ofC class is treated as ʻA class. In other words, super () in C class points to ʻA class`.

Next, if you look at ʻA class, there is B classin the relationship of siblings. Thesuper function is also for accessing sibling classes, so super () in ʻA class will point to B class.

All that remains is the B class, but the B class has no parents. There is a ʻA classas a sibling relationship, but since Python is clever, it will ignore the relationship that you have traced once. So there is nothing thatsuper () of B class` points to.

As a result, the order is B-> A-> C. It's a little confusing, but did you understand?

The Mixin class

Is it close to trait in PHP? ** If you think "A new one is coming out ..." **, don't worry. This is just a story of multiple inheritance.

First of all, a sample.

# coding=utf8

class Mixin(object):
    def say(self):
        print('Hoge!!!!!')

class Human(Mixin, object):
    pass  #pass means "do nothing".

class Cat(Mixin, object):
    pass

human = Human()
human.say()

cat = Cat()
cat.say()

The Human class and Cat class inherit multiple ʻobject classes and Mixin classes, respectively. It's really just multiple inheritance, but the reason why I give different titles and tell the same story again is ** because it is easy to add functions to multiple classes **. PHP's traitwas also a mechanism for easily adding functions to multiple classes. The same thing can be expressed usingmultiple inheritance` in Python.

Most of the usage of multiple inheritance in Python is Mixin class. I think it will be used in Django, so please remember it!

By the way, in this example, the Mixin class is a subclass of the ʻobject class, so both the Human classand theCat class` can be defined as follows.

class Human(Mixin):
    pass  #pass means "do nothing".

class Cat(Mixin):
    pass

It's just a story of inheritance. ..

Summary

This time I introduced how to create a class and inherit it. It feels complicated because there are many things that can be done, but it is very convenient and fun to master!

What should I do next? It is undecided. ..

Recommended Posts

Getting Started with Python for PHPer-Classes
Getting Started with Python for PHPer-Functions
1.1 Getting Started with Python
Getting Started with Python
Getting Started with Python
Getting Started with Python for PHPer-Super Basics
Getting Started with Python Functions
Getting Started with Python Django (1)
Getting Started with Python Django (4)
Getting Started with Python Django (3)
Getting Started with Python Django (6)
Python3 | Getting Started with numpy
Getting Started with Python Django (5)
[Translation] Getting Started with Rust for Python Programmers
Settings for getting started with MongoDB in python
Getting Started with Python responder v2
Getting Started with Python Web Applications
Getting Started with Julia for Pythonista
Getting Started with Python Basics of Python
Getting Started with Google App Engine for Python & PHP
Getting Started with Python Genetic Algorithms
Getting started with Python 3.8 on Windows
Getting Started with python3 # 1 Learn Basic Knowledge
Getting Started with Python Web Scraping Practice
Getting Started with Python Web Scraping Practice
Getting started with Dynamo from Python boto
Getting Started with Lisp for Pythonista: Supplement
Django 1.11 started with Python3.6
Getting started with Android!
Getting Started with Golang 2
Getting started with apache2
Getting Started with Golang 1
Getting Started with Django 1
Getting Started with Optimization
Getting Started with Golang 3
Getting Started with Numpy
Getting started with Spark
Getting Started with Pydantic
Getting Started with Golang 4
Getting Started with Jython
Getting Started with Django 2
Building a Windows 7 environment for getting started with machine learning with Python
Getting started with Python with 100 knocks on language processing
Getting started with AWS IoT easily in Python
Materials to read when getting started with Python
Translate Getting Started With TensorFlow
Getting Started with Tkinter 2: Buttons
Getting Started with Go Assembly
Getting Started with PKI with Golang ―― 4
Get started with Python! ~ ② Grammar ~
Getting Started with Django with PyCharm
Getting Started with python3 # 2 Learn about types and variables
Get started with Python! ~ ① Environment construction ~
Getting Started with python3 # 3 Try Advanced Computations Using Import Statements
Getting Started with Git (1) History Storage
Getting started with Sphinx. Generate docstring with Sphinx
Getting Started with Sparse Matrix with scipy.sparse
How to get started with Python
Getting Started with Mathematics Starting with Python Programming Challenges Personal Notes-Problem 1-1
Getting Started with Cisco Spark REST-API
started python