Python – Object Oriented

実行している内容は、Java – Object Oriented と同じ
– __init__()は初期化のための特殊メソッド
– self引数は、インスタンス化された個別のオブジェクト自体を参照することを示している

Class Code

class Dog:
    """ This is a Dog Class """

    # Initializer
    def __init__(self, name, breed, age):
        self.name = name
        self.breed = breed
        self.age = age

    def sayBreed(self):
        print(self.name)

    def sayAge(self):
        print(self.age)

    def sayIntroduction(self):
        print(f'I am {self.name},{self.breed} and age is {self.age}.')


if __name__ == ('__main__'):
    dog1 = Dog("Kevin", "Bulldog", 3)
    dog2 = Dog("Kaito", "Shibaken", 2)

    dog1.sayIntroduction()
    dog2.sayIntroduction()

Run a Class

import dog_class

a_dog = dog_class.Dog("Susan", "Poodle", 4)
a_dog.sayIntroduction()

b_dog = dog_class.Dog("Anthony", "Shepard", 2)
b_dog.sayIntroduction()
$python ./dog_use.py
I am Susan, Poodle and age is 4.
I am Anthony, Shpard and age is 2.

[参考] Java – Object Oriented

Class Code

package JavaPackage;

public class Dog {

    // attributes
    public String breed;
    public int age;
    public String name;

    // methods
    public void sayBreed() {
        System.out.println(this.breed);
    }

    public void sayAge() {
        System.out.println(this.age);
    }

    public void sayIntroduction() {
        System.out.println("I am " + this.name + ","
                + this.breed + " and age is " + this.age + ".");
    }

    // Constructor
    public Dog(String name, String breed, int age) {
        this.name = name;
        this.breed = breed;
        this.age = age;
    }

    public Dog() {
        this("noName", "Breed of Dog", 0);
    }
}

package JavaPackage;

public class CallMethod {
    public static void main(String[] args) {

        // Instantiation
        Dog dog1 = new Dog("Kevin", "bulldog", 3);
        Dog dog2 = new Dog("Kaito", "Shibaken", 2);
        Dog dog0 = new Dog();

        // call method
        dog1.sayIntroduction();
        dog2.sayIntroduction();
        dog0.sayIntroduction();

    }
}