getters and setters in python
class Person: # Constructor def __init__(self, name, age): # Since we making getters and setters, we should mangle the varible names to make them "private" by adding 2 underscores. self.__name = name self.__age = age # Getters def get_name(self): return __self.name def get_age(self): return __self.age # Setters def set_name(self, new_name): self.__name = new_name def set_age(self, new_age): self.__age = new_age
python class getters and setters
class A(): """Defines a class A with x and y attribute""" def __init__(self, x, y): """Every instance of A has x and y attributes""" self.__x = x #private instance attribute x self.__y = y #private instance attribute y def GetX(self): """Retrieves the x attribute""" return self.__x def GetY(self): """Retrieves the y attribute""" return self.__y def SetX(self, x): """sets the x attribute""" self.__x = x def SetY(self, y): """sets the y attribute""" self.__y = y
Source: python-course.eu
Python Class Without Getters and Setters
class Celsius: def __init__(self, temperature = 0): self.temperature = temperature def to_fahrenheit(self): return (self.temperature * 1.8) + 32