This is a continuation from Functions. This time I will explain about the class!
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())
Class definition is done using class
as in PHP.
Like the ʻif statementand
function, the scope is represented by
indentinstead of
{}. Again, don't forget the
: (colon)` at the end of the class definition.
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.
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.
Needless to say, the constructor method name
is different.
PHP is __construct
, and Python is __init __
.
** 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 **.
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 as
init. 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). ..
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.
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())
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):
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)
How Python supports multiple inheritance of classes! It's a convenient multiple inheritance, but it tends to be complicated, so use it with caution.
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):
** 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 the
B 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
.
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!
The definition of C class
isclass C (A, B):
, and ʻA classis declared first. In this case, the immediate parent of
C 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. The
super 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 that
super () of
B class` points to.
As a result, the order is B-> A-> C
.
It's a little confusing, but did you understand?
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 using
multiple 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 the
Cat 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. ..
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