User defined data type where we give a name to the data type.
This data type can contain many variables indies of it with each variable possibly being of different data types, and each variable can have it's own name.
* A class must start with a capital letter.
A variable inside a class
You can have functions inside of a class. You call functions inside of a calls a mehtod.
An object is an instance of a particular class.
Pythons internal reference identifier for classes.
use self.color when declaring. Omnit when initalizing. You can then set it to an intialized class outside.
You MUST have self as the first argument of that funciton.
self allows for public vairables. If self is not infront of a method variable it is a private variable.
A void function doens't retrun anything.
Special type of method. Automatically run when a class is intialized.
two underscores def init():
# the name of the data thype (class) msut always start with a capital letter. class My_data_type: #First letter of a class must be capitalized! def init_some_vals(self,val2): # self is first argument of function self.first_var = 1.7 # attributes named self.attribute_name self.second_var = val2 def multiply_vals(self): # internal method that returns a value return self.first_var*self.second_var me = My_data_type() # declare an object of the class. Parens are calling an automatic initalizer. me.init_some_vals(2.2) print(me.first_var) print(me.multiply_vals()) # run a method
me.third_var=231.3 # Allowed to create a new variable not defined in the class but not good logical practice. print(me.third_var)
class Pet: def __init__(self,animal_type,name,age,weight_lbs,color): #Example Intializer self.animal = animal_type self.name = name self.age = age self.weight_lbs = weight_lbs self.color = color self.weight_kg = self.calc_weight_in_kg() def calc_weight_in_kg(self): return 0.453592*self.weight_lbs def describe_pet(self): print('This pet is a',self.color, self.animal,) print('This pet\'s name is',self.name,'and it is',self.age,'years old') print('This pet weighs',self.weight_lbs,'pounds, which is',round(self.weight_kg,2),'kilograms')
my_cat = Pet('cat','Ophelia',0.5,3,'liver') my_cat.describe_pet() my_dog = Pet('dog','Tes',5,51,'liver') my_dog.describe_pet() my_dog2 = Pet('dog','Willow',5,103,'Black') my_dog2.describe_pet()
This pet is a liver cat This pet's name is Ophelia and it is 0.5 years old This pet weighs 3 pounds, which is 1.36 kilograms This pet is a liver dog This pet's name is Tes and it is 5 years old This pet weighs 51 pounds, which is 23.13 kilograms This pet is a Black dog This pet's name is Willow and it is 5 years old This pet weighs 103 pounds, which is 46.72 kilograms
my_cat.weight_lbs=5 # can change values of intilized objects print(my_cat.weight_lbs)# changed weight in pounds print(my_cat.weight_kg) # did not change the weight in KG since initializer didn't run. my_cat.weight_kg=my_cat.calc_weight_in_kg() print(my_cat.weight_kg)
5 1.360776 2.26796