Attributes | COMP70050: Introduction to Machine Learning | Department of Computing | Imperial College London home article Introduction to Machine Learning COMP70050 Autumn Term 2021/2022 Introduction to Python for Java programmers The Zen of Python Example Python program Python vs. Java - Main method Python vs. Java - Variable declaration Python vs. Java - Semicolons Python vs. Java - Braces Python vs. Java - Comments Running Python Running Python as a script Running Python interactively Basic built-in data types Everything is an object Reserved words Variables - Java vs. Python Python Variables Objects in Python Operators Assignment operator Lists Accessing Lists Modifying Lists Tuples Strings are sequences Formatting strings Sets Dictionaries Grouping data with dict and tuple Control flow Loops Useful objects for loops List comprehensions Functions Function arguments Built-in functions Object-Oriented Programming in Python Constructor Attributes Methods Magic/Dunder methods Inheritance Encapsulation Encapsulation the Pythonic way What about protected? Python modules Custom modules What's in a __name__? Handling text files Reading CSV files Writing to CSV files Handling JSON files Pickle That's a wrap! Attributes Let us now look at how you declare and initialise instance attributes (or instance variables), as well as use it. In Java, you declare instance variables directly in the class declaration. In Python, you dynamically attach new instance variables to the self object inside __init__() (Remember that self has only been allocated some space in memory at this point). This is where you initialise any attributes and their values (Lines 3-6). 1
2
3
4
5
6
7
8
9
10
11
12
13
class Person:
def __init__(self, firstname, lastname, age=0):
self.firstname = firstname
self.lastname = lastname
self.age = age
self.friends = []
person = Person("Josiah", "Wang", 20) # What do you mean I don't look 20? :D
print(person.firstname)
print(person.lastname)
person.age = person.age + 1
print(person.age)
Like a normal function, you may assign default values for any of the arguments (e.g. age=0 in Line 2) Accessing/updating the value of the attributes is just like in Java, with a dot (.) operator (Lines 9-13) The attributes are public by default. What about private attributes? Hold that thought, we’ll come to that later! << Previous Next >> Page designed by Josiah Wang Department of Computing | Imperial College London