Object Oriented Programming/Properties
Appearance
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, the property
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 using obj.attribute1
class MyClass:
def __init__(self, attribute1, attribute2):
self._attribute1 = attribute1
self._attribute2 = attribute2
@property
def attribute1(self):
return self._attribute1
@attribute1.setter
def attribute1(self, value):
# Perform any validation or custom logic here
self._attribute1 = value
# Usage example
obj = MyClass("Value 1", "Value 2")
print("Attribute 1:", obj.attribute1)
#Using property to add in new values
obj.attribute1 = "New Value 1"
print("Updated Attribute 1:", obj.attribute1)
sss
class Animal:
def __init__(self, species, name, age):
self._species = species
self._name = name
self._age = age
# Getter methods
@property
def species(self):
return self._species
@property
def name(self):
return self._name
@property
def age(self):
return self._age
# Setter methods
@name.setter
def name(self, new_name):
self._name = new_name
@age.setter
def age(self, new_age):
self._age = new_age
# Other methods
def make_sound(self):
pass
def move(self):
pass