Creating classes dynamically in python [duplicate] - python

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)

Related

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

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.

Why can't I reference a global variable defined in a class? [duplicate]

This question already has answers here:
How can I access "static" class variables within methods?
(6 answers)
Closed 3 years ago.
class MyClass(object):
code_mapping = {...}
def get_name(code):
code = code_mapping[code]
...
In this piece of code, it complains that 'code_mapping is not defined'. Isn't code_mapping is accessible to everything within MyClass?
Initialize it with self. This will make it accessible by any function in the class by passing it with self.<variable> and then passing self as a function argument to anything you want to pass the variable to.
class MyClass(object):
def __init__(self):
self.code_mapping = {...} # if this will be a hard coded
def get_name(self):
code = self.code_mapping[code]
...
Or you could do:
class MyClass(object):
def __init__(self, code_mapping):
self.code_mapping = code_mapping
def get_name(self):
code = self.code_mapping[code]
...
if you'd like to pass some code mapping as an argument to your class at its instantiation.
To create a class object from this where you want {'code1' : 'name'} you then initiate a class object like this:
code1 = MyClass({'code1' : 'name'})
And then {'code1' : 'name'} will be what is carried forth into whatever get_name() does and the value of code in get_name will be name.

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)

Is this a bug in Python inheritance? [duplicate]

This question already has answers here:
Why do attribute references act like this with Python inheritance? [duplicate]
(3 answers)
How to avoid having class data shared among instances?
(7 answers)
Closed 10 years ago.
I'm not sure if the output of this code is correct or a bug:
class F:
"""An abstract class"""
list_of_secrets = []
def __init__(self):
pass
def getSecret(self):
return self.list_of_secrets
class F_None(F):
pass
class F_Some(F):
def __init__(self):
self.list_of_secrets.append("secret value!")
x = F_Some()
print "x:",x.getSecret()
y = F_None()
print "y:",y.getSecret()
The output using python 2.7.3:
x: ['secret value!']
y: ['secret value!']
I think it should output:
x: ['secret value!']
y: []
Any thoughts?
list_of_secrets is scoped to the class here. You want to instead attach it to self in __init__
def __init__(self):
self.list_of_secrets = []
You never define self.list_of_secrets. You only define F.list_of_secrets, which is entirely different. Do this instead:
class F:
"""An abstract class"""
def __init__(self):
self.list_of_secrets = []
def getSecret(self):
return self.list_of_secrets

Calling an inherited property in python [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Polymorphism in Python
Hi
I'm trying to call a property in a class, that is inherited from my baseclass, but it doesn't work. I guess I'm missing something, but what?
Here is my code:
class Produkt:
def __init__(self,pID,pProdNavn,pNetto):
self.__produktId = pID #atributt for produkt nummer
self.__produktNavn = pProdNavn #atributt for produkt navn
self.__produktNetto = pNetto #egenskap for nettopris
def getName(self): #Metode for å finne produktnavnet
return self.__produktNavn
class Bok(Produkt):
def __init__(self,pID,pProdNavn,pNetto,pForfatter):
Produkt.__init__(self,pID,pProdNavn,pNetto)
self.__produktForfatter = pForfatter #atributtp for forfatter
def getNet(self):
return self.__produktNetto
as you see I'm trying to call the _productNetto property that is inherited from my Produkt class.
What am I doing wrong?
/Andy
It works fine if you don't use double underscore in attribute names
class Produkt:
def __init__(self,pID,pProdNavn,pNetto):
self.produktId = pID
self.produktNavn = pProdNavn
self.produktNetto = pNetto
def getName(self):
return self.__produktNavn
class Bok(Produkt):
def __init__(self,pID,pProdNavn,pNetto,pForfatter):
Produkt.__init__(self,pID,pProdNavn,pNetto)
self.produktForfatter = pForfatter
def getNet(self):
return self.produktNetto
x = Bok(1, 2, 3, 4)
print x.getNet()
output:
3
Otherwise the names get mangled and it is looking for attribute _Bok__produktNetto. See: http://docs.python.org/reference/expressions.html#atom-identifiers
AttributeError: Bok instance has no attribute '_Bok__produktNetto'
The problem is that you named those members with two leading underscores, which makes them invisible under those names outside that class (see http://docs.python.org/tutorial/classes.html).
If you rename those fields with a single underscore in both places, it will work as you intend.

Categories