Write a program that will accept 5 words from the user. Print these words in alphabetical order.
Take a user input of form MM/DD/YYYY, convert it into a string of form Day Month Year and print the string. You will need to split the string that the user enters at the / characters (use the split() method) and then use the three substrings to construct a new string. For example, input of 11/21/1989 would produce output 21 November 1989.
Creating a custom class:
class Maciatko:
def zamnaukaj(self):
print("Mňau!")
Inside the class body, we can define methods using the def keyword, but they have the first parameter self. Notice that the class name starts with a capital letter.
Creating an object:
murko = Maciatko()
Calling a method:
murko.zamnaukaj()
Creating custom attributes:
murko.meno = 'Murko'
The self parameter:
class Maciatko:
def zamnaukaj(self):
print(f"{self.meno}: Mňau!")
murko = Maciatko()
murko.meno = 'Murko'
micka = Maciatko()
micka.meno = 'Micka'
murko.zamnaukaj()
micka.zamnaukaj()
A method can also have additional parameters after self. When calling a method, we omit the self parameter—it is filled in automatically—but we use the other parameters like normal function arguments. For example, in this case the string ‘fish’ is assigned to the parameter jedlo (food):
class Maciatko:
def zamnaukaj(self):
print(f"{self.meno}: Mňau!")
def zjedz(self, jedlo):
print(f"{self.meno}: Mňau mňau! {jedlo} mi chutí!")
murko = Maciatko()
murko.meno = 'Murko'
murko.zjedz('ryba')
What happens if we forget to give the kitten a name? The zamnaukaj method will stop working.
To prevent this error, we can ensure that every kitten must have a name as soon as it is created. The user will then provide the name when creating the Maciatko object:
murko = Maciatko(meno='Murko')
This call does not work yet—we need to modify the Maciatko class.
We will use a special method called init (two underscores before and after the method name). The underscores indicate that this method is special. Python calls it automatically when creating a new object.
class Maciatko:
def __init__(self, meno):
self.meno = meno
def zamnaukaj(self):
print(f"{self.meno}: Mňau!")
def zjedz(self, jedlo):
print(f"{self.meno}: Mňau mňau! {jedlo} mi chutí!")
murko = Maciatko('Murko')
murko.zamnaukaj()
Now it is no longer possible to create a kitten without a name, because we cannot create the object without providing the meno parameter. Therefore, the zamnaukaj method will always work.
We can pass the kitten’s name as a positional argument (Python deduces which variable the value belongs to based on its position), or we can use a named argument:
# 'Murko' is the value of the first argument for __init__ (after self)
murko = Maciatko('Murko')
# 'Micka' is the value of the 'meno' argument
micka = Maciatko(meno='Micka')