Object Oriented Programming/Properties
Tools
General
Sister projects
In other projects
Properties in OOP are also able to be looked at as functions, a property houses a function that can have its procedures or variables altered without directly going to the code and editing it. A property can be changed or updated based on user input which allows for a lot of user-interactive programs and applications.'
In Python, theproperty keyword allows you to define getter, setter, and deleter methods for class attributes, making them act like properties. This enables you to control the access and modification of class attributes while providing a clean interface for external code. In example , we use the@property decorator to create getter methods for each attribute, allowing us to access these attributes usingobj.attribute1
classMyClass:def__init__(self,attribute1,attribute2):self._attribute1=attribute1self._attribute2=attribute2@propertydefattribute1(self):returnself._attribute1@attribute1.setterdefattribute1(self,value):# Perform any validation or custom logic hereself._attribute1=value# Usage exampleobj=MyClass("Value 1","Value 2")print("Attribute 1:",obj.attribute1)#Using property to add in new valuesobj.attribute1="New Value 1"print("Updated Attribute 1:",obj.attribute1)
sss
classAnimal:def__init__(self,species,name,age):self._species=speciesself._name=nameself._age=age# Getter methods@propertydefspecies(self):returnself._species@propertydefname(self):returnself._name@propertydefage(self):returnself._age# Setter methods@name.setterdefname(self,new_name):self._name=new_name@age.setterdefage(self,new_age):self._age=new_age# Other methodsdefmake_sound(self):passdefmove(self):pass