I have this class signature (the init signature):
class TensorDataset(Dataset):
def __init__(self, *tensors)
this class is initialized in this line:
dataset = TensorDataset(all_input_ids, all_attention_mask, all_token_type_ids, all_labels)
now I would like to wrap the this class, so I created CustomDataset:
class CustomDataset(Dataset):
def __init__(self, *tensors, **keywords):
self.tensor_dataset = TensorDataset(*tensors)
self.all_text = keywords["all_text"]
and I also tried:
class CustomDataset(Dataset):
def __init__(self, *tensors, all_text=None):
self.tensor_dataset = TensorDataset(*tensors)
self.all_text = all_text
But when I try to initialize this class like this:
dataset = CustomDataset(all_input_ids, all_attention_mask, all_token_type_ids, all_labels, all_text: all_text)
I get an error:
End of statement expected
Statement expected, found Py:RPAR
What am I doing wrong?
I'm not sure what are you trying with all_text: all text, but named args should go like
all_text=all_text
so try that.
Related
I am trying to create a json string from a class and I defined my class as follows:
import json
import ast
from datetime import datetime
import pytz
import time
class OuterClass:
def __init__(self):
self.Header = None
self.Body = None
class Header:
def __init__(self, ID = None, Name = None):
self.ID = ID
self.Name = Name
class Body:
def __init__(self, DateTime=None, Display=None):
self.DateTime = DateTime
self.Display = Display
def current_time_by_timezone(timezone_input):
return datetime.now(pytz.timezone(timezone_input))
if __name__ == '__main__':
response = OuterClass()
header = response.Header('123', 'Some Name')
body = response.Body(current_time_by_timezone('US/Central'), 'NOT VALID')
print(json.dumps(response.__dict__))
I'm getting an error 'TypeError: 'NoneType' object is not callable'. Is it because I'm setting the Header and Body in the OuterClass definition myself to None?
The problem with your code is these lines:
self.Header = None
self.Body = None
These create instance variables named Header and Body on every instance of OuterClass, so you can never access the class variables (the nested classes) via an instance, only via OuterClass itself.
It's not very clear what your intention is with this data structure. Defining a class inside another class doesn't do anything special in Python (by default, you could probably make there be special behavior with special effort, like using a metaclass that makes the inner classes into descriptors). Generally though, there's no implied relationship between the classes.
If you want your OuterClass to create instances of the other two classes, you can do that without nesting their definitions. Just put the class definitions at top level and write a method that creates an instance at an appropriate time and does something useful with it (like binding it to an instance variable).
You might want something like:
def Header:
...
def Response:
def __init__(self):
self.header = None
def make_header(self, *args):
self.header = Header(*args)
return self.header
You could keep the classes nested as long as you don't expect that to mean anything special, just be sure that you don't use the class name as an instance variable, or you'll shadow the name of the nested class (a capitalization difference, like self.header vs self.Header could be enough).
I want to know how can I pass argument from a class to two different functions inside. I import this file, called test.py and I have to pass two arguments (name_t,name_s) from another file suppose caledl passing.py. So I want to do is like this (I know it's wrong but it is to explain my point):
(passing.py)
from test import M
name_t = 'tomas'
name_s = 'santino'
M(name_t,name_s)
(test.py)
class M():
def values():
tapi = name_t
def loop():
symbol = name_s
Use an __init__() method to get the parameters and set attributes.
class M():
def __init__(self, name_t, name_s):
self.tapi = name_t
self.symbol = name_s
def values(self):
print(self.tapi)
def loop(self):
print(self.symbol)
name_t = 'tomas'
name_s = 'santino'
m = M(name_t, name_s)
m.values()
m.loop()
import copy
class Myclass0:
paperlist=[]
class Myclass1:
def copy_something(self):
Paper = Myclass0()
Flowers = ["Roses","Sunflower","Tulips","Marigold"]
Paper.paperlist = copy.copy(Flowers)
class Myclass3:
superlist = []
Paper = Myclass0()
print(Paper.paperlist)
superlist.append(paperlist[0])
I am getting a index out of range error on compiling.please help me finding a way to print paperlist of Myclass0 in Myclass3 using class Myclass1 Functions and attributes.You can change the class body but All the Classes should be used.
I am waiting for your valuable efforts.
Thank You
maybe this code snippet could help you understand it better:
class MyClass0:
def __init__(self):
# this is now an attribute of the instance (not the class)
self.paperlist = []
class MyClass1:
#staticmethod
def copy_something(paper):
# this is a static method (it doesnt rely on the Class (MyClass1) or an instance of it
flowers = ["Roses", "Sunflower", "Tulips", "Marigold"]
paper.paperlist = flowers
class Myclass3:
def __init__(self, paper):
# when an instance of this class is created an instance of MyClass0
# must pre passed to its constructor. It then prints out its paperlist
print(paper.paperlist)
paper = MyClass0()
MyClass1.copy_something(paper)
Myclass3(paper)
I'm trying to implement a method for which is necessary to use recursion, but every time, I get the global name not defined error
My class look like this:
class MyClass(object):
def _init_(self, name=None, content=None):
self.name = name
self.content = content
It's a node class, name it's just a text string and content a list of it's children (they are nodes too), is initialized as None but the construction function that builds the tree give them a blank list if they have no children. The class works fine and so does the function but if I try to add recurtion to methods they just don't work, even if they work just fine as a standalone function, i.e.:
def get_nodes(self):
c = []
c.append(self.name)
if self.content != []:
for a in self.content:
c.extend(get_nodes(a))
return c
I know this is possible, what am I doing wrong?
You need to do a.get_nodes().
Also the initialization method is called __init__, not _init_ (two underscores on both ends).
Edit: If you won't show your code, we can't tell you what's wrong with your code. This code works for me:
class MyClass(object):
def __init__(self, name=None, content=None):
self.name = name
self.content = content
def get_nodes(self):
c = []
c.append(self.name)
if self.content != []:
for a in self.content:
c.extend(a.get_nodes())
return c
>>> n = MyClass('me', [])
>>> m = MyClass('other', [n])
>>> m.get_nodes()
['other', 'me']
If your code doesn't work then you have to explain how your code is different from that.
I have a model where I want to use a class method to set the default of for a property:
class Organisation(db.Model):
name=db.StringProperty()
code=db.StringProperty(default=generate_code())
#classmethod
def generate_code(cls):
import random
codeChars='ABCDEF0123456789'
while True: # Make sure code is unique
code=random.choice(codeChars)+random.choice(codeChars)+\
random.choice(codeChars)+random.choice(codeChars)
if not cls.all().filter('code = ',code).get(keys_only=True):
return code
But I get a NameError:
NameError: name 'generate_code' is not defined
How can I access generate_code()?
As I said in a comment, I would use a classmethod to act as a factory and always create you entity through there. It keeps things simpler and no nasty hooks to get the behaviour you want.
Here is a quick example.
class Organisation(db.Model):
name=db.StringProperty()
code=db.StringProperty()
#classmethod
def generate_code(cls):
import random
codeChars='ABCDEF0123456789'
while True: # Make sure code is unique
code=random.choice(codeChars)+random.choice(codeChars)+\
random.choice(codeChars)+random.choice(codeChars)
if not cls.all().filter('code = ',code).get(keys_only=True):
return code
#classmethod
def make_organisation(cls,*args,**kwargs):
new_org = cls(*args,**kwargs)
new_org.code = cls.generate_code()
return new_org
import random
class Test(object):
def __new__(cls):
cls.my_attr = cls.get_code()
return super(Test, cls).__new__(cls)
#classmethod
def get_code(cls):
return random.randrange(10)
t = Test()
print t.my_attr
You need specify the class name: Organisation.generate_code()