Here, we will explain the basics of "classes" for beginners in Python. It is assumed that you are using Python 3 series.
Use class
when creating a class.
class_1.py
class Human:
name = 'Yukiya'
def say_hello():
return 'Hello.'
print(Human.name)
print(Human.say_hello())
You can create a class as described above, but with this writing method, you cannot create an instance other than "Yukiya" for name
.
Use __init__
to allow you to freely set the name
later.
The first argument is self
.
class_2.py
class Human:
def __init__(self, n):
self.name = n
def say_hello(self):
return 'Hello,' + self.name + 'is.'
yukiya = Human('Yukiya')
takada = Human('At most')
print(yukiya.name)
print(yukiya.say_hello())
print(takada.name)
print(takada.say_hello())
"Inheritance" is to create a "child class" with additional functions based on an existing "parent class".
class_3.py
class Human:
def say_hello(self):
return 'Hello'
class Japanese(Human):
def say_konnichiwa(self):
return 'Hello.'
yukiya = Japanese()
print(yukiya.say_hello()) #You can also use methods of the Human class.
print(yukiya.say_konnichiwa())
Here, I explained the basics of "classes" in Python. It's a necessary idea for object-oriented programming, so make sure you understand it.
What is the programming language Python? Can it be used for AI and machine learning?
Recommended Posts