Class and Instance Attributes

Leocj
3 min readJan 15, 2020

--

After an introduction to Object Oriented Programming in Python, one can have some confusion about differences between attributes when this belongs to a an Object or a Class. So let’s make this clear using examples.

Next I’m going to put the full code (in parts) for a class definition and how can we use it to understand the details about instances.

class Dog: #Class name (definition)
“””Represents a dog, with a name.””” #docstring for the class

population = 0 # public CLASS attribute, class variable, shared var
_year = 2020 # public CLASS attribute. For convention is internal.
year_ = 2021 # public CLASS attribute. Avoid conflicts with keywords
__password = None # private CLASS attribute.
__word__ = None # Magic object of python, don’t modify.

# @ are DECORATORS, shortcut to wrapper function. For example @classmethod
# is equivalent to how_many = classmethod(how_many)
# do something before or after the inner function),

# INSTANCE method called.
# Can modify object instance state.
# Can modify class state.
# obj = Dog(); obj.method() → Ok
# Dog.method() → TypeError
def method(self): # Can use self, object itself.
“””Prints population.””” #docstring for the method
print(“We have {:d} dogs.”.format(self.population))

# CLASS method called
# Can’t modify object instance state.
# Can modify class state.
# obj = Dog(); obj.classmethod() → OK
# Dog.classmethod() → OK
@classmethod # Can use cls, the class itself.
def classmethod(cls):
“””Prints population.””” #docstring for the method
print(“We have {:d} dogs.”.format(cls.population))

# STATIC metod called.
# Can’t modify object instance state.
# Can’t modify class state.
# obj = Dog(); obj.staticmethod() → OK
# Dog.staticmethod() → OK
@staticmethod # Can’t use cls, self
def staticmethod():
“””Prints something.””” #docstring for the method
print(“We have dogs.”)

# Decorator, shortcut to wrapper function. how_many = classmethod(how_many)
@classmethod # do something before or after the inner function),
def how_many(cls):
“””Prints the current population.””” #docstring for the method
print(“We have {:d} dogs.”.format(cls.population))

def __init__(self, name=””, hei=0, wei=0): #Three external user parameter
“””Initializes the data.”””
self.name = name # public INSTANCE attribute, object variable, owned
Dog.population += 1 # Using class variable

def bark(self): # Instance method
“””I am barking.”””
print(“{} dog bark”.format(self.name))

### getter and setter for private variable. From outside looks like public
using this property methods.
@property # Property wrap
def x(self): # getter method
return self.__x

@x.setter # setter wrap for x property
def x(self, x): # setter method
if x < 0:
self.__x = 0
elif x > 1000:
self.__x = 1000
else:
self.__x = x

# Destructor method.
# Custom destructor marks item as uncollectable.
# called when object is deleted, using del obj.
def __del__(self): # called when the program finish.
# body of destructor

def func():
func.counter = getattr(func, “counter”, 0) + 1

def main():
Dog().bark() # Prints dog bark

Dog(‘Swaroop’).bark() # Prints Swaroop dog bark

spot = Dog(“Spot”, 30, 40)
spot.bark() # Prints Spot dog bark

bowser = Dog()
bowser.name = “Bowser”
bowser.bark() # Prints Bowser dog bark

#### Class variables ####
Dog.population += 1 # Modify. For all instances of Class Dog
print(Dog.population) # Prints 5. Us of global for all instances of Dog
# try to access spot.population, Python checks first, if “population” is a
# key of spot.__dict__ If it is not, Python checks, if is a key of the
# Dog.__dict__ If so, the value can be retrieved.
print(spot.population) # Prints 5. Same value of the Dog class
spot.population +=2 # Modify. Only for sport instance of Class Dog
# If Dog.population is modified, spot.population no
print(spot.population) # Prints 7. Incorrect use of global variable.
print(Dog.population) # Prints 5. Us of global for all instances of Dog

#### Object variable ####
spot.name = “sport” # Modify. Just for spot instance
print(spot.name) # Print sport. Use of instance attribute.

#print(Dog.__password) # Error. __password is private.
Dog._year = 2019 # Internal use variable modification
print(Dog._year) # Prints 2019

Dog.how_many() # Prints We have 5 dogs.

print(Dog.__doc__) # Class documentation (docstrings)
print(Dog.how_many.__doc__) # Method documentation (docstrings)
help(Dog) # Full description

spot.owner = “Bob” # dynamically create arbitrary new attributes
print(spot.__dict__) # Prints dictionary existing instances of a class

print(getattr(spot, ‘age’, 2)) # Prints 2. third argument is default value

#func.counter = 0 # Bind attribute to function
func() # Have an attribute that works as static variable
print(func.counter) # Prints 1
func()
print(func.counter) # Prints 2

main()

--

--

Leocj
0 Followers

Holberton School Software Engineer Student.