Un-Wrap or De-Inherit an object [duplicate] - python

This question already has answers here:
How do I call a parent class's method from a child class in Python?
(16 answers)
Closed 1 year ago.
A code block I do not have access to, returns an object that is "wrapped" or rather inherited from a base class, that I want to recover. The wrapper is harmful, I want to get rid of it. Is there a way to upcast to the parent class? To unwrap the object? To disinherit it?
I prepared a simple example: Is it possible to manipulate the u object in a way that it will be a Person object and say hello in a nice way?
class Person():
def __init__(self, name):
self.name = name
def say_hello(self):
print("Hi, my name is " + self.name)
class Unfriendly_Person(Person):
def say_hello(self):
print("Leave me alone!")
u = Unfriendly_Person("TJ")
u.say_hello()

You might assign to __class__, so
class Person():
def __init__(self, name):
self.name = name
def say_hello(self):
print("Hi, my name is " + self.name)
class Unfriendly_Person(Person):
def say_hello(self):
print("Leave me alone!")
u = Unfriendly_Person("TJ")
u.__class__ = Person
u.say_hello()
output:
Hi, my name is TJ
But rememeber that this will jettison all methods from Unfriendly_Person even these not defined in Person.

Related

Creating classes dynamically in python [duplicate]

This question already has answers here:
How can I dynamically create derived classes from a base class
(4 answers)
Closed 10 months ago.
Is it a good coding practice to have the class name as variable.
E.g
def create_class(class_name):
class class_name:
def __init__(self):
do_sth....
class_instance = class_name()
return class_instance
for object in objects:
res = create_class(object)
I wanted to create different classes which are present in a list like objects=[person,vehicle, location ..]. What could be other alternative way to do it ?
class_name is a class, you can set a name property for your class, like this:
class class_name:
def __init__(self,name):
self.name = name
def __str__(self):
return str(self.name)
objects=["person","vehicle","location"]
for obj in objects:
res = class_name(obj)
print(res)

How can I make the OOP code print my classes objects name?

I've tried to make an OOP based program in python. I gave it an object to work with and tried to make it print the name, but its not working.
class human:
def __init__(self, name):
print("this is a human")
def name(self, name):
print("this is {}".format(bob.name))
bob = human("bob")
Anyone know what the problem could be?
Beyond the answers you already received (which solve your problem), I'd suggest not having a method that prints the name. Rather, you should have a __str___ dunder method that defines the object's behavior when an instance is printed.
class human:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
person = human("bob")
print(person)
'bob'
You can also define the object's behavior when the instance name is entered in the console, for instance just running the line
>>> person
You can do it with __repr__:
def __repr__(self):
return f'when entering the instance name in the console: {self.name}'
This will print:
when entering the instance name in the console: bob
This appears more pythonic to me than having a method that simply prints the name.
You're never storing the name on the instance, where would it get the name from? Your __init__ needs to do something along the lines of self.name = name
the name method and attribute are going to conflict, the latter will shadow (hide) the former, and it should look up whatever attribute its using on self
You never assigned the passed name to the object. Try:
class human:
def __init__(self, name):
print("this is a human")
self.name = name
def print_name(self):
print("this is {}".format(self.name))
bob = human("bob")
bob.print_name()
there are couple of things to update in the code:
bob is an instance which is not defined at human class
notice that init, name functions expect external param but you never use it in the function. (in self. = name)
in order to use it:
define a var in the class named 'name' and update you function to:
class human:
_name = ""
def __init__(self, name):
print("this is a human")
self._name = name
def name(self):
print("this is "+ self._name)
bob = human("bob")
bob.name()
bob = human("bob") only init function and you should call bob.name() in order to call the print-name function

Printing __init__ object from list Python error [duplicate]

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 4 years ago.
I am trying to print an object from a list based on my class settings.
from math import *
import time
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
people = [MyClass("David",17),
MyClass("George",63),
MyClass("Zuck",12),
MyClass("Mark",18)
]
print(people[2])
But it prints out this: <main.MyClass object at 0x0000000003129128>
I want it to print "Zuck"
That's because your array contains objects, so when you print them, they are printed as an object representation. I realize that what you want is to print its content.
For that you have to specify how you want to present the instance when printed, using the method __str__:
from math import *
import time
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "name: {}, age: {}".format(self.name, self.age)

How to specify Type Hint for Parameters for Custom Classes? [duplicate]

This question already has answers here:
Using the class as a type hint for arguments in its methods [duplicate]
(3 answers)
Closed 5 years ago.
Let's say that I have created a class defined below, and I have called methods on it:
class Student:
def __init__(self, name):
self.name = name
self.friends = []
def add_friend(self, new_friend: Student):
self.friends.append(new_friend)
student1 = Student("Brian")
student2 = Student("Kate")
student1.add_friend(student2)
The method add_friend has a parameter called new_friend, which is a Student object. How do I use type hints to specify that? I assumed that you just have to simply enter the name of the class, like new_friend: Student but it does not work. When I run it, I get a NameError: name 'Student' is not defined. I also tried new_friend: __main__.Student, but it gives me the same error. What am I doing wrong?
Per PEP-484, use the string name of the class for forward references:
class Student:
def __init__(self, name):
self.name = name
self.friends = []
def add_friend(self, new_friend: 'Student'):
self.friends.append(new_friend)

__init__ and the setting of class variables

Im having some trouble understanding Inheritance in classes and wondering why this bit of python code is not working, can anyone walk me through what is going wrong here?
## Animal is-a object
class Animal(object):
def __init__(self, name, sound):
self.implimented = False
self.name = name
self.sound = sound
def speak(self):
if self.implimented == True:
print "Sound: ", self.sound
def animal_name(self):
if self.implimented == True:
print "Name: ", self.name
## Dog is-a Animal
class Dog(Animal):
def __init__(self):
self.implimented = True
name = "Dog"
sound = "Woof"
mark = Dog(Animal)
mark.animal_name()
mark.speak()
This is the output through the terminal
Traceback (most recent call last):
File "/private/var/folders/nd/4r8kqczj19j1yk8n59f1pmp80000gn/T/Cleanup At Startup/ex41-376235301.968.py", line 26, in <module>
mark = Dog(Animal)
TypeError: __init__() takes exactly 1 argument (2 given)
logout
I was trying to get animal to check if an animal was implemented, and then if so, get the classes inheriting from animal to set the variables that Animals would then be able to manipulate.
katrielalex answered your question pretty well, but I'd also like to point out that your classes are somewhat poorly - if not incorrectly - coded. There seems to be few misunderstandings about the way you use classes.
First, I would recommend reading the Python docs to get the basic idea: http://docs.python.org/2/tutorial/classes.html
To create a class, you simply do
class Animal:
def __init__(self, name, sound): # class constructor
self.name = name
self.sound = sound
And now you can create name objects by calling a1 = Animal("Leo The Lion", "Rawr") or so.
To inherit a class, you do:
# Define superclass (Animal) already in the class definition
class Dog(Animal):
# Subclasses can take additional parameters, such as age
def __init__(self, age):
# Use super class' (Animal's) __init__ method to initialize name and sound
# You don't define them separately in the Dog section
super(Dog, self).__init__("Dog", "Woof")
# Normally define attributes that don't belong to super class
self.age = age
And now you can create a simple Dog object by saying d1 = Dog(18) and you don't need to use d1 = Dog(Animal), you already told the class that it's superclass is Animal at the first line class Dog(Animal):
To create an instance of a class you do
mark = Dog()
not mark = Dog(Animal).
Don't do this implimented stuff. If you want a class that you can't instantiate (i.e. you have to subclass first), do
import abc
class Animal(object):
__metaclass__ = abc.ABCMeta
def speak(self):
...
Since age in the given example is not part of the parent (or base) class, you have to implement the the function (which in a class is called method) in the class which inheritted (also known as derived class).
class Dog(Animal):
# Subclasses can take additional parameters, such as age
def __init__(self, age):
... # Implementation can be found in reaction before this one
def give_age( self ):
print self.age

Categories