Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagepy
titleA Python class
 class Student:
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

    def is_old(self):
        return self.age > 100

The __init__() method is the closest thing Python has to a constructor. Notice the use of self.nameto initialize the state of the instance. Also included is the simple method is_old() to determine (in a slightly "ageist" manner) whether the underlying student is young or old (with "old" being over 100 years).

The code in Listing 1 listing illustrates one of the great merits of OO programming: Code and data reside in close proximity to each other. Data is of course the repository of state, so the use of OO brings code, data, and state together in a manner useful to programmers. Clearly, you can do all of this without OO code, but OO makes it a matter of rather beautiful simplicity.

Code Block
languagejava
titleA Java student class
public class Student {
	String name; 
	int age; 
	String major; 
	public Student() { 
		// TODO Auto-generated constructor stub } 	
	public Student(String name, int age, String major) { 
		this.name = name; 	
		this.age = age; 
		this.major = major; 
	} 
}
The Java code in Listing 2 this listing is very similar to the Python code in Listing 1previous. Notice that the use of OO can produce quite readable code in either language. Listing 1 Python listing is not likely to baffle a Java programmer, even without a background in Python. Likewise, a Python programmer well versed in the Python OO features would easily understand the Java code in Listing 2the second listing.