this constructor takes no arguments: python - python

import random
import sys
import os
class Animal :
__name=""
__height=0
__weight=0
__sound=0
def __init__(self, name, height, weight, sound):
self.__name=name
self.__height=height
self.__weight=weight
self.__sound=sound
def set_name(self,name):
self.__name =name
def get_name(self):
return self.__name
def set_height(self,height):
self.__height =height
def get_height(self):
return str(self.__height)
def set_weight(self,weight):
self.__weight =weight
def get_weight(self):
return str(self.__weight)
def set_sound(self,sound):
self.__sound =sound
def get_sound(self):
return self.__sound
def get_type(self):
print("Animal")
def toString(self):
return"{} is {} cm tall and {} kilograms and say{}".format(self.__name, self.__height,self.__weight,self.__sound)
cat = Animal('ruby',33,10,'meow')
print(cat.toString())
Error message:
Traceback (most recent call last):
File "python", line 37, in <module>
TypeError: this constructor takes no arguments

class methods should be indented to be within the class
import random
import sys
import os
class Animal :
__name=""
__height=0
__weight=0
__sound=0
def __init__(self, name, height, weight, sound):
self.__name=name
self.__height=height
self.__weight=weight
self.__sound=sound
def set_name(self,name):
self.__name =name
def get_name(self):
return self.__name
def set_height(self,height):
self.__height =height
def get_height(self):
return str(self.__height)
def set_weight(self,weight):
self.__weight =weight
def get_weight(self):
return str(self.__weight)
def set_sound(self,sound):
self.__sound =sound
def get_sound(self):
return self.__sound
def get_type(self):
print("Animal")
def toString(self):
return"{} is {} cm tall and {} kilograms and say{}".format(self.__name, self.__height,self.__weight,self.__sound)
cat = Animal('ruby',33,10,'meow')
print(cat.toString())
This results in
ruby is 33 cm tall and 10 kilograms and saymeow

classes have to be defined in one block. Also getters and setters are disadvised. The class-attributes should be deleted, because they are set as instance attributes.
class Animal:
type = "Animal"
def __init__(self, name, height, weight, sound):
self.name = name
self.height = height
self.weight = weight
self.sound = sound
def __str__(self):
return "{0.name} is {0.height} cm tall and {0.weight} kilograms and say {0.sound}".format(self)
cat = Animal('ruby',33,10,'meow')
print(cat)

Related

Achieving single-responsibility principle with python abstract classes

I want to separate the DB models from the actual classes. But i need two static functions for fetching data from the DB regardless of the subclass type. the implementation for both functions are the same across all DB models.
pyright showing an error that cls inside get() and get_all() functions doesn't have a db property.
from abc import ABC, abstractstaticmethod
class DogsDB:
lists = ["DOG1", "DOG2", "DOG3"]
#classmethod
def get(cls, id):
return cls.lists[id]
class CatsDB:
lists = ["CAT1", "CAT2", "CAT3"]
#classmethod
def get(cls, id):
return cls.lists[id]
class Animal(ABC):
def __init__(self, name):
self.name = name
#abstractstaticmethod
def save(m):
pass
#abstractstaticmethod
def _from_model(obj):
pass
#classmethod
def get(cls, id):
obj = cls.db.get(id)
return cls._from_model(obj)
#classmethod
def get_all(cls):
objs = cls.db.lists
lists = []
for obj in objs:
e = cls._from_model(obj)
lists.append(e)
return lists
def __repr__(self):
return self.name
class DogSound:
def __init__(self, name):
self.name = name
def sound(self):
print(self.name, ": DOG SOUND!!")
class Dog(Animal, DogSound):
db = DogsDB
def __init__(self, name, age):
super(Dog, self).__init__(name)
self.age = age
#staticmethod
def save(m):
print(m)
#staticmethod
def _from_model(obj):
return Dog(obj, 4)
class Cat(Animal):
db = CatsDB
def __init__(self, name, age):
super().__init__(name)
self.age = age
#staticmethod
def save(m):
print(m)
#staticmethod
def _from_model(obj):
return Cat(obj, 4)
print(Cat.get(1))
print(Dog.get(1))
print(Cat.get_all())
print(Dog.get_all())
Dog.get(1).sound()
I cannot duplicate your first error.
Your second issue is a result of method sound implicitly returning None since it has no return statement and you have print(Dog.get(1).sound()), which will print out the return value from that method. You either want to change this to just Dog.get(1).sound() or modify the sound method to return what it is currently being printed and remove the print statement (my choice).
As an aside, I found this class structure a bit difficult to follow. Why do you need a separate DogSound class with a name attribute which should belong to Animal? Also, it seems to me that age could/should be an attribute of Animal since both cats and dogs have an age.
from abc import ABC, abstractstaticmethod
class DogsDB:
lists = ["DOG1", "DOG2", "DOG3"]
#classmethod
def get(cls, id):
return cls.lists[id]
class CatsDB:
lists = ["CAT1", "CAT2", "CAT3"]
#classmethod
def get(cls, id):
return cls.lists[id]
class Animal(ABC):
def __init__(self, name, age):
self.name = name
self.age = age
#abstractstaticmethod
def save(m):
pass
#abstractstaticmethod
def _from_model(obj):
pass
#classmethod
def get(cls, id):
obj = cls.db.get(id)
return cls._from_model(obj)
#classmethod
def get_all(cls):
objs = cls.db.lists
lists = []
for obj in objs:
e = cls._from_model(obj)
lists.append(e)
return lists
def __repr__(self):
return self.name
class Dog(Animal):
db = DogsDB
def __init__(self, name, age):
super().__init__(name, age)
def sound(self):
return f"{self.name}: DOG SOUND!!"
#staticmethod
def save(m):
print(m)
#staticmethod
def _from_model(obj):
return Dog(obj, 4)
class Cat(Animal):
db = CatsDB
def __init__(self, name, age):
super().__init__(name, age)
self.age = age
#staticmethod
def save(m):
print(m)
#staticmethod
def _from_model(obj):
return Cat(obj, 4)
print(Cat.get(1))
print(Dog.get(1))
print(Cat.get_all())
print(Dog.get_all())
print(Dog.get(1).sound())
Prints:
CAT2
DOG2
[CAT1, CAT2, CAT3]
[DOG1, DOG2, DOG3]
DOG2: DOG SOUND!!
If for some reason you want DogSound to be a separate class, then there is no need for the name attribute to be duplicated:
...
class DogSound: # A "Mixin" class
def sound(self):
return f"{self.name}: DOG SOUND!!"
class Dog(Animal, DogSound):
db = DogsDB
def __init__(self, name, age):
super().__init__(name, age)
#staticmethod
def save(m):
print(m)
#staticmethod
def _from_model(obj):
return Dog(obj, 4)
...

Python - TypeError: module.__init__() takes at most 2 arguments (3 given)

Trying my hand at Python inheritance. I need your help on how to fix an error.
I have 2 classes: Person (super class )& Contact (sub class).
I get the following error when trying to run Contact:
"Contact.py", line 3, in <module>
class Contact(Person):
TypeError: module.__init__() takes at most 2 arguments (3 given)
Thanks in advance
Below is my code:
class Person:
__name=""
__age=0
def __init__(self, name, age):
self.__name = name
self.__age = age
def set_name(self, name):
self.__name = name
def set_age(selfself, age):
self.__age = age
def get_name(self):
return self.__name
def get_age(selfself):
return self.__age
def getInfo(self):
return "Name is: {} - Age is: {}".format(self.__name, self.__age)
# ----------------------------------------------------
import Person
class Contact(Person):
__method=""
def __init__(self, name, age, method):
super().__init__(name, age)
self.__method = method
def set_method(self, method):
self.__method = method
def get__method(self):
return self.__method
def getInfo(self):
return "Name is: {} - Age is: {} - Contact Info: {}".format(self.__name, self.__age, self.__method)
person2 = Contact("Adam Smith", 19, "Email: adam.smith#abcde.net")
print(person2.getInfo())
First of all, the indentation is messed up!
If Person is in a separate file, import the file name without extension, like this:
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def set_name(self, name):
self.__name = name
def set_age(self, age):
self.__age = age
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def getInfo(self):
return "Name is: {} - Age is: {}".format(self.__name, self.__age)
# ----------------------------------------------------
from person import Person # assumed your Person class is in person.py
class Contact(Person):
__method=""
def __init__(self, name, age, method):
super().__init__(name, age)
self.__method = method
def set_method(self, method):
self.__method = method
def get__method(self):
return self.__method
def getInfo(self):
return "Name is: {} - Age is: {} - Contact Info: {}".format(self.get_name(), self.get_age(), self.__method)
person2 = Contact("Adam Smith", 19, "Email: adam.smith#abcde.net")
print(person2.getInfo())
Access the parent class's private fields through its methods.

AttributeError: 'Dog' object has no attribute 'get_height'

Should you need it, the tutorial I am following is Python Programming by #Derek Banas:
This lesson is demonstrating class object inheritance
class Animal:
__name = ""
__height = 0
__weight = 0
__sound = 0
def __init__(self, name, height, weight, sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
def get_type(self):
print("Animal")
def toString(self):
return "{} is {} cm tall and {} kilograms and {}".format(self.__name,
self.__height,
self.__weight,
self.__sound)
cat = Animal('Whiskers', 33, 10, 'Meow')
print(cat.toString())
class Dog(Animal):
__owner = ""
def __init__(self, name, height, weight, sound, owner):
self.__owner = owner
super(Dog, self).__init__(name, height, weight, sound)
def set_owner(self, owner):
self.__owner = owner
def get_owner(self):
return self.__owner
def get_type(self):
print("Dog")
def toString(self):
return "{} is {} cm tall & {} kgrms and {} hi
{}".format(self.get_name(),
self.get_height(),
self.get_weight(),
self.get_sound(),
self.get_owner())
""" I am getting this runtime error message python version 3.6
Here is the error:
File "C:/Watson/HDM/tutorial_py1.py", line 192, in toString
self.get_height(),
AttributeError: 'Dog' object has no attribute 'get_height' """
Dog object is not having any attribute 'get_height' as get_height() function is not declared in the class before. You need to add the method in the class:
def get_height(self, name):
return self.__height

How to get class inheritence working in Python?

I am supposed to create a class called Dog(Animal) which is inheriting from Class Animal. However after I run this code, I got errors that I do not understand:
The problem is solved, no further questions that I see at the moment
class Animal:
__name = ""
__height = 0
__weight = 0
__sound = 0
def __init__(self, name, height, weight, sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
#def set_name(self, name):
#self.__name = name
def get_name(self):
return self.__name
def get_height(self):
return str(self.__height)
def get_weight(self):
return str(self.__weight)
def get_sound(self):
return self.__sound
def get_type(self):
print("Animal")
def toString(self):
return "{} is {} cm tall and {} kilograms and says{}".format(self.__name,
self.__height,
self.__weight,
self.__sound)
cat = Animal('pussy', 33, 10, 'meow')
print(cat.toString())
print(cat.get_type())
print(cat.get_sound())
class Dog(Animal):
__owner = ""
def __init__(self, name, height, weight, sound, owner):
self.__owner = owner
super(Dog, self).__init__(name, height, weight, sound)
def set_owner(self, owner):
self.__owner = owner
def get_owner(self):
return self.__owner
def get_type(self):
print("Dog") # Dog object
def toString(self):
return "{} is {} cm tall and {} kilograms and says{} its owner is {}".format(self.__name,
self.__height,
self.__weight,
self.__sound,
self.__owner)
spot = Dog("kaili", 22, 33, "woof", "Jiahui")
print(spot.toString())
Change this line:
class Animal:
to this:
class Animal(object):
This post explains it quite well.
After I added metaclass = type at the beginning, the problem is solved. I am not quite sure but seems the metaclass allows python2.7 to access python3's library.

Python Inheritance - Instance Has No Attribute

I'm new to python and just trying to test the syntax and get to know it.
The code below works fine except for when I get to inheritance. The final command "toString" function is not working and I can't for the life of me figure out why.
I'm sure I'm not doing something the most efficient way, but even if there's a more efficient way I'd first like to understand why what I'm doing is wrong. thanks a lot. Please let me know if I need to clarify anything
#!/bin/python
class Animal:
__name = ""
__height = 0
__weight = 0
__sound = 0
def __init__(self, name, height, weight, sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
def set_name(self,name):
self.__name = name
def get_name(self):
return self.__name
def set_height(self,height):
self.__height = height
def get_height(self):
return self.__heiight
def set_weight(self,weight):
self.__weight=weight
def get_weight(self):
return self.__weight
def set_sound(self,sound):
self.__sound = sound
def get_sound(self):
return self.__sound
def get_type(self):
print("Animal")
def toString(self):
return("{} is {} inches tall, {} lbs, and says {}".format(self.__name, self.__height,self.__weight,self.__sound))
objCat = Animal('Whiskers', 33, 10, 'Meow')
print (objCat.toString())
# Attempt Inheritance
class cDog(Animal):
__owner=""
def __init__(self,name,height,weight,sound,owner):
self.__owner=owner
Animal.__init__(self,name,height,weight,sound)
def __str__(self):
return ("{}".format(self.__height))
def set_owner(self,owner):
self.__owner=owner
def get_owner(self):
return self.__owner
def get_type(self):
print("Dog")
def toString(self):
return ("{} is {} inches tall, {} lbs, says {}, and is owned by, {}".format(self.__name,self.__height,self.__weight,self.__sound,self.__owner))
objDog = cDog('Brewsky', 20, 75, 'Ruff', 'Jared')
print (objDog.toString())
In your Animal class, the double underscore before the name of the attributes has made them (sort of) private.
Just delete the double underscore (or change it to one underscore, if you want to keep a weak indicator) and it will be fixed.
See this question for more information.

Categories