Class and instance attributes

Dog class

0. Definitions

1. Code examples

>>> class Dog:
... """
... Create a "Dog" class
... """
... def __init__(self, name, weight, age, address):
... """
... Constructor
... Args:
... name (string): 'name' instance attribute
... weight (int): 'weight' instance attribute
... etc...
... """
#this is a private instance attribute:
... self.__name = name
#these are public instance attribute:
... self.weight = weight
... self.age = age
... self.address = address
...    def Characteristics(self):
... """
... Create a "Characteristics" instance method
... """
...
print("{} weighs {}kg and is {} year(s) old."
.format(self.name, self.weight, self.age))
... @property
... def name(self):
... """
... Create the name getter
... """
... return self.__name
... @name.setter
... def name(self, value):
...
"""
... Create the name setter
... """
... if type(value) is not int:
... raise TypeError("Name must be a string !")
... else:
... self.__name = value

2. User manipulations:

>>> Labrador = Dog(Poopie, 25, 9, garden, female)
>>> Labrador.Characteristics()
Poopie weighs 25kg and is 9 year(s) old.
>>> Labrador.name = "Loolee"
>>> Labrador.name
Loolee
>>> Labrador.name = 98
>>> Labrador.name
TypeError: Name must be a string !
>>> Labrador.__dict__
{'name': Poopie, 'weight': 25, 'age': 9, 'address': garden}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store