Invictus Invictus - 9 months ago 50
Python Question

Looks like base class constructor not initialized

I am a newbie in python and trying my hands in oops programming here.
I am initializing base class constructor in derived class , but when trying to print its attribute in base class it gives me error

object has no attribute

import random
import os
import sys
class Animal:
__name =""
def __init__(self,name):
self.__name = name
def toString(self):
return "{} is the animal name".format(self.__name)
def get_name(self):
return self.__name
cat = Animal("natasha")
print (cat.toString())
class Dog(Animal):
__owner = ""
def __init__(self,name,owner):
self.__owner= owner
super(Dog, self).__init__(name)
def toString(self):
return "{} is Animal. And owner is: {}".format(self.__name,self.__owner)
rocky = Dog("rocky","Ronchi")
print (rocky.toString())

What am i doing wrong here ? I tried like calling
also which was a getter function instead of
but this also did not work.I am working on python3.4


This is why you must not use double-underscore prefixes for your instance attributes. These are name mangled, and almost never do what you expect.

Just use and self.owner everywhere.